How do I stop movement once a the player hits a wall?
Hi, unity noob here. I have a box as a terrain; floor and 4 walls. So far the movement is almost done except for one thing, making the player stop moving once he hits a wall. The code I have is this -
public class Movement : MonoBehaviour {
public int mSpeed = 10;
Collider playerColl;
void Start () {
playerColl = this.GetComponent<BoxCollider>();
}
void Update () {
if(Input.GetKey(KeyCode.S)){
transform.Translate(mSpeed*Time.deltaTime,0f,0f);
}
if(Input.GetKey(KeyCode.D)){
transform.Translate(0f,0f,mSpeed*Time.deltaTime);
}
if(Input.GetKey(KeyCode.W)){
transform.Translate(-mSpeed*Time.deltaTime,0f,0f);
}
if(Input.GetKey(KeyCode.A)){
transform.Translate(0f,0f,- mSpeed*Time.deltaTime);
}
}
}
The issue Im having is, since the movement is done like above, the player effectively ignores all colliders in the scene. How do I make it not ignore collision?
Answer by IgorAherne · Dec 24, 2016 at 08:50 PM
add a rigidbody to the player, without it the coliders won't register colliision with one another. If there are any colliders which are moving in your scene, - always attach rigidbody to them. Also, if you don't do this, it hits physics performance hard.
Answer by Sky84 · Dec 24, 2016 at 11:41 PM
Hello @acuppatea, in Unity there already a collision detection. Try to add a Rigidbody. Just a question : It's a 2D game ? Because if there is a 2D game, remove the Boxcollider Component and add the BoxCollider2D. and it should works
Sorry for bad english.
Your answer
![](https://koobas.hobune.stream/wayback/20220612103342im_/https://answers.unity.com/themes/thub/images/avi.jpg)