Hi guys,
I am working on a 2D Game and I would like to measure or assign a Movement Speed for the character, any ideas how can I get this done?
My goal is to have a value that represent the speed of the character and be able to modify the value depending on the character.
Here is the code i am using:
public class Player_Movement : MonoBehaviour
{
private BoxCollider2D boxCollider;
private Vector3 moveDelta;
private RaycastHit2D hit;
// Test Speed
public float MoveSpeed = 3.0f;
private void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
}
private void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
// Reset MoveDelta
moveDelta = new Vector3(x,y,0);
// Swap sprite direction, wether you are going right or left
if (moveDelta.x < 0)
transform.localScale = Vector3.one;
else if (moveDelta.x > 0)
transform.localScale = new Vector3(-1, 1, 1);
// Make sure you can move in this direction by casting a box there first, if the box returns null we are free to move
hit = Physics2D.BoxCast(transform.position,boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("Player","Blocking"));
if(hit.collider == null)
{
// Make this thing move
transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
}
hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Player", "Blocking"));
if (hit.collider == null)
{
// Make this thing move
transform.Translate(moveDelta.x * Time.deltaTime, 0, 0);
}