- Home /
The question is answered, right answer was accepted
How to to stop my box from moving when using OnControllerColliderHit
I have a player (capsule) and a cube game object. To the player object I have attached a character controller and a behavior script, which has the following OnControllerColliderHit method in it.
void OnControllerColliderHit(ControllerColliderHit hit) {
Rigidbody body = hit.collider.attachedRigidbody;
//checking whether rigidbody is either non-existant or kinematic
if (body == null || body.isKinematic)
return;
if (hit.moveDirection.y < -.3f)
return;
//set up push direction for object
Vector3 pushDirection = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
body.velocity = 2.0f * pushDirection;
}
My cube then has a rigigbody (Which has enabled all rotation constraints) and box collider attached to it. When my player moves into the cube It begins to be pushed away, as intended, but here comes my problem!
PROBLEM: When My cube has been pushed by the player, then when I move my player away from the cube, the cube still keeps moving, and doesn't stop. My intention was that the cube should only be pushed as long as my player was 'hitting' it. When the player was moving away, then the cube should stop moving.
I hope you can help me with this problem!
Answer by Andres-Fernandez · May 28, 2014 at 09:05 AM
The problem is that you set a velocity for the cube's rigidbody when you detect the collision:
body.velocity = 2.0f * pushDirection;
That adds a velocity to the cube, but you never reset that velocity to 0, which would make it stop moving. You must set the velocity of the cube back to 0 when the contact finishes.
How do I check if contact has finished?
I can't find a method called OnControllerColliderHitExit()
Have you tried adding force to the object ins$$anonymous$$d of setting velocity?
Adding force ins$$anonymous$$d of velocity makes the same result. So how can I check if I doesn't hit the cube anymore?
You could attach a collider to the cube, make it trigger and use OnTriggerExit().
Follow this Question
Related Questions
How to use AddForce on FPC 0 Answers
Character Controller goes through objects 2 Answers
Character Sliding before animation starts 1 Answer
Why isn't my character jumping?? 1 Answer