- Home /
Moving a 2d player and preventing them from passing through objects
I've been tooling with a few movement options, but at the moment I'm not sure how to set it up correctly. I'm calling my Move() function in Update, the plan is to have the player rotate towards the key input, and be moving forward while there is input. Transform.Translate doesn't allow for easy physics integration, so I was hoping someone could point out what I'm missing in the code.
Player has non kinematic rigidbody and box collider. Solid object has non kinematic rigidbody and box collider, and is tagged 'Solid'.
private void Move()
{
float horizontal = Input.GetAxisRaw("p" + playerId + "MoveHorizontal");
float vertical = Input.GetAxisRaw("p" + playerId + "MoveVertical");
Quaternion targetAngle;
if (horizontal != 0 || vertical != 0)
{
float angle = Mathf.Atan2(vertical, horizontal) * Mathf.Rad2Deg;
targetAngle = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, targetAngle,
Time.deltaTime * rotationSpeed);
Vector3 fwd = transform.TransformDirection(Vector3.forward);
rigidbody.velocity = transform.right * Time.deltaTime * movementSpeed;
}
else
{
rigidbody.velocity = transform.right * 0;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Solid")
{
rigidbody.velocity = transform.right * 0;
}
}
What exactly, is the problem?, is the player passing through these solid objects or something else?
Yes, my player is passing through them. I believe it has to do with setting the velocity ins$$anonymous$$d of adding forces.
Answer by tanoshimi · Oct 24, 2016 at 03:59 PM
If you want to use 2D physics, you need a Rigidbody2D mot a RigidBody and your objects should have BoxCollider2Ds, not BoxColliders.
Your answer
Follow this Question
Related Questions
2D Detect collisions of a 2D block only on left/right (not top/bottom) 0 Answers
Audio Source Play On Collision 2D? 3 Answers
2D, collision with background 0 Answers
Load Scene on Either Edge of Camera Collision 2 Answers
Find out that player is not grounded 2 Answers