- Home /
Tricky issue involving knockback and the player.
I am working on a project where I cannot alter the player character, and I cannot add anything to it. So I need to figure out a way to knock back the player when the player enters a collison.
I am having a lot of problems trying to figure this out because I can't figure out how to get an object's rigidbody that collides when it collides with the object that is supposed to knockback.
Here is the script I have so far using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Knockback : MonoBehaviour
{
public float force = 30;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Player")
{
Vector3 dir = col.contacts[0].point - transform.position;
dir = -dir.normalized;
GetComponent<Rigidbody>().AddForce(dir * force);
}
}
}
What I want to happen, is for the player to collide with an object, and knock them back. I cannot attach anything to the player, or attach any part of the player to the script in any way. Does anyone have an idea of how to do this? anything will help. thank you
Answer by Ermiq · Sep 01, 2018 at 05:46 AM
Well, if you can't attach this script to the player (can't see why you couldn't do that though), then you need to attach this script to an object which is supposed to knock the player back.
You also need to modify the script in that case.
public class Knockback : MonoBehaviour
{
public float force = 30;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Player")
{
Vector3 dir = col.contacts[0].point - transform.position;
//dir = -dir.normalized; you don't need this here, because it will reverse the direction.
//now, without this line the direction will point from the transform (object) to the player.
col.rigidbody.AddForce(dir * force);
// that's how you get the player's rigidbody
}
}
}
That does exactly what I need. I can't tell you why I cant access the player character because I am under a Non-Disclosure. I know its really weird, believe me...I know.
I do however have another issue. But, I will post it as another question. Thank you for your help!
Ah, ok, I see.
By the way, I forgot about normalizing direction vector. Vector3 dir = (col.contacts[0].point - transform.position).normalized;
. Otherwise, the force applied to rigidbody will depend on the distance between the player and the object's pivot point.
thank you. The other question is not co$$anonymous$$g up with anything. The issue is the player will get shot through walls sometimes or the floor if you hit the object at the right angle. how would I fix that?