- Home /
Character Collision Issue
I created my own, simple movement script in Unity. However, collision does not seem to be working. The cube this script it applied to has a box collider and so do the objects I want it to collide with. The cube just passes right through though. Thoughts?
var moveSpeed:float = 1;
function Update () {
var h = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
var v = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
transform.position += transform.TransformDirection(Vector3(h,0,v));
}
Adding a Rigidbody Component to the cube works. However, I don't want it to be a rigidbody. Is there some really simple thing I'm overlooking???
Check out this tutorial on Unity Gems - basically make your rigidbody kinematic or if you are using a character controller then move it with Simple$$anonymous$$ove
Answer by kromenak · Nov 14, 2012 at 11:57 PM
LONG EXPLANATION
An important thing to realize is that a "collider" in Unity is nothing more than a coded description of an area in 3D space. For example, there is nothing explicitly solid about a box collider; it is just a position vector and a size vector that can be taken to represent a box of a certain size at a certain position in the 3D world.
You'll notice in your code above that you are simply updating transform.position in response input. Nothing in your code is checking to see if a collider is in the way and responding appropriately. In fact, the code required to check for colliders and respond appropriately can be split into collision handling and physics code, both of which are fairly complicated and probably not things you'd want to code yourself - they could potentially be huge chunks of code!
Most likely, you are expecting Unity to handle collisions for you, but the only way it can do that is if you are using a Rigidbody or a Character Controller. A Rigidbody will give you both collision and physics functionality, while a character controller seems to mainly be collision detection. Both these components do the work of detecting colliders in the environment and disallowing movement when there is a collision.
SHORT ANSWER
You can use CharacterController.Move to move while also taking collisions into account. When you call Move, the Character Controller will attempt to move if there is space, or stop moving if there is a collider in the way.
If you use a Rigidbody with Kinematic turned on, you'll get collisions and physics when things hit, but you will still be able to move through static colliders - probably not what you are looking for.