- Home /
strange behaviour after object collision
I have an object that I can control to solve a maze via WASD. The problem is that when it collides with a wall (not always), the movement pattern changes. For example, if I go forward and straight into a wall by pressing "W", after the collision, the "W" key doesn't move the object forward anymore, but left (for example) and the same for the other keys ("S" to move right, etc.). If I collide again, the pattern sometimes changes too, to the point of fixing the previous collision's mess or making it worse (object bouncing, moving in diagonal when pressing a single key, etc.) The script for the movement is fairly simple:
if (Input.GetKey("w") )
gameObject.transform.Translate(new Vector3(speed, 0, 0) *Time.deltaTime);
}
if (Input.GetKey("s"))
{
gameObject.transform.Translate(new Vector3(-speed, 0, 0 ) * Time.deltaTime);
}
if (Input.GetKey("d") )
{
gameObject.transform.Translate(new Vector3(0, 0, -speed) * Time.deltaTime);
}
if (Input.GetKey("a") )
{
gameObject.transform.Translate(new Vector3(0, 0, speed) * Time.deltaTime);
}
My object has a sphere collider, box collider and rigidbody and the walls have a box collider. The plane that plays the role of the ground has a box collider.
Answer by cdnDave · May 07, 2019 at 04:29 PM
I am guessing this is happening because your object is rotating due to the collision. By default the Transform.Translate function applies the movement relative to objects local axes which will change when the object rotates. There is an optional paramater that you can pass into the Translate function with which you can tell it to use the world space axes instead, I suspect this will solve the problem.
i.e.
gameObject.transform.Translate(new Vector3(speed, 0, 0) *Time.deltaTime, Space.World);
More information about this can be found in the docs https://docs.unity3d.com/2018.3/Documentation/ScriptReference/Transform.Translate.html