- Home /
Stop player cube from going trough the walls
I have made my own script to make a simple 2D game and the player is a basic cube. I have created a script to move the cube with Vector3. So when I test, the player can go trough the walls. I tried to make it a rigidbody but it just glitches and then flied away. I also freezed some positions but that bugged out. So if someone can tell me how I can fix this, please. :)
My player code:
function Update ()
{
if(Input.GetKey("w")) {
transform.position += Vector3.forward * Time.deltaTime * 3;
}
if(Input.GetKey("a")) {
transform.position += Vector3.left * Time.deltaTime * 3;
}
if(Input.GetKey("s")) {
transform.position += Vector3.back * Time.deltaTime * 3;
}
if(Input.GetKey("d")) {
transform.position += Vector3.right * Time.deltaTime * 3;
}
}
Answer by mattssonon · Oct 03, 2013 at 03:02 PM
Colliders don't work when you're changing position like that, since you're basically teleporting the cube. You need to use a CharacterController or a RigidBody component. For instance, if you add a CharacterController you can then use CharacterController.Move() to move the cube and have it collide with colliders.
Answer by Gamegineer · Oct 03, 2013 at 03:26 PM
The walls and the cube should have collider components attached. Verify the "size" in all the colliders are not zero, (1,1) should be good for most cases.
If they already had colliders attached, problem may be with setting the transform directly, which bypasses the collision detection. Instead try moving the cube via the rigid body
Your answer
Follow this Question
Related Questions
How do i stop player to move when dead 2 Answers
Player is moving through walls when force is added from a knockback script? *UNANSWERED* 3 Answers
Enemy is not stopping following the player 2 Answers
Dive collide 2 Answers
How do I stop the enemy ai from following the player after it dies on unity3d properly in C# 0 Answers