Using the following code to control a top down 2D character. Movement works fine until I run into a wall or any object, then it starts to drift without input in a random direction. I’m sure this has something to do with the physics but not sure what.
public class Player : MonoBehaviour {
public Transform target;
public float speed;
public Text healthDisplay;
public int health = 10;
public bool isRunning = false;
public float RunSpeed;
public float NormalSpeed;
private Rigidbody2D rb;
private Vector2 moveVelocity;
void Start(){
rb = GetComponent<Rigidbody2D>();
}
void Update(){
//healthDisplay.text = "HEALTH: " + health;
if(health <= 0){
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
//Player faces mouse direction
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}
void FixedUpdate(){
//Normal movement
Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveVelocity = moveInput.normalized * speed;
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
//Sprinting
if(Input.GetKey(KeyCode.LeftShift)){
isRunning = true;
speed = RunSpeed;
} else {
isRunning = false;
speed = NormalSpeed;
}
}
}