84 lines
2.4 KiB
C#
84 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
using Prism;
|
|
|
|
namespace Example
|
|
{
|
|
class PlayerCube : Entity
|
|
{
|
|
public float HorizontalForce = 10.0f;
|
|
public float JumpForce = 10.0f;
|
|
|
|
private RigidBody2DComponent m_PhysicsBody;
|
|
private MaterialInstance m_MeshMaterial;
|
|
|
|
int m_CollisionCounter = 0;
|
|
|
|
public Vec2 MaxSpeed = new Vec2();
|
|
|
|
private bool Colliding => m_CollisionCounter > 0;
|
|
|
|
void OnCreate()
|
|
{
|
|
m_PhysicsBody = GetComponent<RigidBody2DComponent>();
|
|
|
|
MeshComponent meshComponent = GetComponent<MeshComponent>();
|
|
m_MeshMaterial = meshComponent.Mesh.GetMaterial(0);
|
|
m_MeshMaterial.Set("u_Metalness", 0.0f);
|
|
|
|
AddCollision2DBeginCallback(OnPlayerCollisionBegin);
|
|
AddCollision2DEndCallback(OnPlayerCollisionEnd);
|
|
}
|
|
|
|
|
|
void OnPlayerCollisionBegin(float value)
|
|
{
|
|
m_CollisionCounter++;
|
|
}
|
|
|
|
void OnPlayerCollisionEnd(float value)
|
|
{
|
|
m_CollisionCounter--;
|
|
}
|
|
|
|
void OnUpdate(float ts)
|
|
{
|
|
float movementForce = HorizontalForce;
|
|
|
|
if (!Colliding)
|
|
{
|
|
movementForce *= 0.4f;
|
|
}
|
|
if (Input.IsKeyPressed(KeyCode.D))
|
|
m_PhysicsBody.ApplyLinearImpulse(new Vec2(movementForce, 0), new Vec2(), true);
|
|
else if (Input.IsKeyPressed(KeyCode.A))
|
|
m_PhysicsBody.ApplyLinearImpulse(new Vec2(-movementForce, 0), new Vec2(), true);
|
|
|
|
if (Colliding && Input.IsKeyPressed(KeyCode.Space))
|
|
m_PhysicsBody.ApplyLinearImpulse(new Vec2(0, JumpForce), new Vec2(0, 0), true);
|
|
|
|
if (m_CollisionCounter > 0)
|
|
m_MeshMaterial.Set("u_AlbedoColor", new Vec3(1.0f, 0.0f, 0.0f));
|
|
else
|
|
m_MeshMaterial.Set("u_AlbedoColor", new Vec3(0.8f, 0.8f, 0.8f));
|
|
|
|
Vec2 linearVelocity = m_PhysicsBody.GetLinearVelocity();
|
|
linearVelocity.Clamp(new Vec2(-MaxSpeed.X, -1000), MaxSpeed);
|
|
m_PhysicsBody.SetLinearVelocity(linearVelocity);
|
|
|
|
if (Input.IsKeyPressed(KeyCode.R))
|
|
{
|
|
Mat4 transform = GetTransform();
|
|
transform.Translation = new Vec3(0.0f);
|
|
SetTransform(transform);
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
}
|