- Home /
Rigidbody2D drifitng after collision
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;
}
}
}
Answer by ayockel90 · Feb 18, 2019 at 06:26 PM
Figured it out, turns out I needed to check the Freeze Rotation box under my character's Rigidbody 2D
Answer by $$anonymous$$ · Feb 18, 2019 at 02:50 AM
I modified your script (I removed the part of your code that doesn't have to do with movement, but you can add that back in later). I changed you rigidbody operation to use velocity rather than MovePosition. Also, I do NOT set the value of speed in the inspector. Speed is automatically set by your code. It's either equal to normal speed or running speed. Tell me what you think:
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed;
public float RunSpeed;
public float NormalSpeed;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
if (Input.GetKey(KeyCode.LeftShift))
{
speed = RunSpeed;
}
else
{
speed = NormalSpeed;
}
}
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(horizontal, vertical);
rb.velocity = movement * speed;
}
}
Your answer
Follow this Question
Related Questions
How to close an open door? 1 Answer
Avoiding 2D top-down diagonal movement 2 Answers
Rigidbody2D x velocity not moving unless placed in FixedUpdate 1 Answer
AddForce() on RigidBody2D does not work when called in certain circumstances 1 Answer
Set player and enemy RigidBodies so that neither can push the other 2 Answers