Question by
jaywyxyr · Aug 06, 2020 at 12:32 AM ·
movementmovement scriptrunning
I have to start moving first to run, and cant start moving in the other direction when running.
Im trying to implement a running feature in my game, using the left shift key to start running. However, I always need to start moving before pressing the shift key to start running. Also, when running in one direction, i cannot change directions. And sometimes, when trying to run to the left, the player character just keeps on moving. This is the script I'm using.
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Animator animator;
public bool isRunning;
Vector2 movement;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
if(Input.GetKey(KeyCode.LeftShift)){
moveSpeed = 6;
isRunning = true;
animator.SetBool("isRunning", true);
}else{
moveSpeed = 3.5f;
isRunning = false;
animator.SetBool("isRunning", false);
}
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Speed", movement.sqrMagnitude);
}
void FixedUpdate()
{
movement = Vector2.ClampMagnitude(movement, 1);
rb.MovePosition(
rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
Thanks in advance.
Comment