I want my player character gameObject to be pushed a short distance away from an enemy it comes in contact with. So I want to use OnCollisionEnter, if colliding object has the tag enemy, for the gameObject to move a short distance in the opposite direction of the enemy object it collided with. How would I go about doing this?
This should accomplish your needs, let me know if you have questions.
void OnCollisionEnter(Collision c)
{
// force is how forcefully we will push the player away from the enemy.
float force = 3;
// If the object we hit is the enemy
if (c.gameObject.tag == "enemy")
{
// Calculate Angle Between the collision point and the player
Vector3 dir = c.contacts[0].point - transform.position;
// We then get the opposite (-Vector3) and normalize it
dir = -dir.normalized;
// And finally we add force in the direction of dir and multiply it by force.
// This will push back the player
GetComponent<Rigidbody>().AddForce(dir*force);
}
}
Assuming you are using rigidbodies with correctly set mass and physics interaction layers…
Inside the OnCollisionEnter function, add this code:
public void OnCollisionEnter(Collision other) {
// how much the character should be knocked back
var magnitude = 5000;
// calculate force vector
var force = transform.position - other.transform.position;
// normalize force vector to get direction only and trim magnitude
force.Normalize();
gameObject.GetComponent<RigidBody>().AddForce(force * magnitude);
}
Hi, I want to make the same think but with kimenatic object, and its not working I have tried to make it with velocity but the object starts to move constantly.
Any suggestions ?,Hi , I want to do the same but with kinematic object, and its not working , i have tried with velocity but the object start to move constantly.
Any suggestions ?