- Home /
Apply explosive force to player at point of contact
Afternoon,
I'm trying to make a player get thrown back when they collide with a flat energy barrier. They're colliding successfully and the enemies react appropriately but the player doesn't seem to be affected by the explosive force.
Any help is appreciated!
public Rigidbody playerBody;
public Rigidbody enemyBody;
public float nudgeForce = 100f;
public float knockMultiplier = 2f;
public float reactionRadius = 2f;
public Vector3 forceOrigin;
void Start()
{
playerMove = GameObject.FindWithTag("Player").GetComponent<PlayerMove>();
healthScript = GameObject.FindWithTag("Player").GetComponent<PlayerHealth>();
playerBody = GameObject.FindWithTag("Player").GetComponent<Rigidbody>();
}
void OnCollisionEnter(Collision other)
{
forceOrigin = other.contacts[0].point;
if (other.gameObject.CompareTag("Player"))
{
playerBody.AddExplosionForce(nudgeForce * knockMultiplier, forceOrigin, reactionRadius, 0, ForceMode.Impulse);
//StartCoroutine(healthScript.MakeInvulnerable());
}
else if (other.gameObject.CompareTag("Enemy"))
{
enemyBody = other.gameObject.GetComponent<Rigidbody>();
enemyBody.AddExplosionForce(nudgeForce * knockMultiplier, forceOrigin, reactionRadius, 0, ForceMode.Impulse);
}
}
}
If a character's movement is based on a Rigidbody
, then it all depends on how the player moves. If you change velocity
directly, then any AddForce()
will be ignored. It is advisable to see how you move the character.
This is the movement script and I've actually got the collision already working relatively to the enemies themselves so maybe it's something about the contact point?
public class PlayerMove : MonoBehaviour { public Rigidbody playerBody; public Transform runCam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
public float turnSmoothVelocity;
[SerializeField] float verticalBoost;
public Vector3 moveDirection;
public Vector3 velocity;
void Start()
{
playerBody = GetComponent<Rigidbody>();
runCam = Camera.main.transform;
//Cursor.lockState = CursorLockMode.Locked; //Seems to help camera control
GetComponent<Rigidbody>().velocity = velocity * Time.deltaTime;
}
void FixedUpdate()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") * verticalBoost);
Vector3 dir = new Vector3(h, 0f, v).normalized;
if(dir.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg + runCam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
playerBody.MovePosition(transform.position + input * Time.deltaTime * speed);
}
}
}
Answer by Borjka · Jul 07, 2021 at 11:54 AM
Hi, - Check if player has right tag - Use Debug.log to see if it goes in the branch where you add forces - Try to increase forces, maybe they are too small
Used otherCollider.tag and otherCollider.attachedRigidbody to check and it's definitely detecting the correct object. Changing force didn't make a difference either. Bizarrely it affects the enemies as intended.
Answer by Harry_Drew · Jul 07, 2021 at 11:57 AM
You're adding a rigidbody to the enemys before you add the explosion force which seems to work. Your not doing that with the player though. Maybe try adding the rigidbody to the player of if the player already has a rigidbody chekc its not in kinematic mode.
PlasticFrames is not an Add, but a Get component of the enemy's Rigidbody
(that is, it already exists):
enemyBody = other.gameObject.GetComponent<Rigidbody>();
And the player also already has a Rigidbody
:
playerBody = GameObject.FindWithTag("Player").GetComponent<Rigidbody>();
Tried this but still no change unfortunately and definitely not kinematic.
Answer by DenisIsDenis · Jul 07, 2021 at 01:20 PM
I've tested your code. Indeed, the player pushes off intermittently, not always. The following code works better in my opinion. In it, I used not the first point of contact, but the arithmetic mean of their coordinate, so that the point of impact on the wall was more accurate. Also I use AddForce()
instead of AddExplosionForce()
, as the behavior of AddForce
is more predictable for me.
void OnCollisionEnter (Collision other)
{
forceOrigin = Vector3.zero;
for (int i = 0; i < other.contacts.Length; i++)
{
forceOrigin += other.contacts [0] .point;
}
forceOrigin /= other.contacts.Length;
if (other.gameObject.CompareTag ("Player"))
{
playerBody.AddForce ((playerBody.position - forceOrigin).normalized * nudgeForce * knockMultiplier, ForceMode.VelocityChange);
}
else if (…)
{
…
}
}
EDITED: @PlasticFrames, I decided to approach the question from the player's perspective. After all, through its OnCollisionEnter (), we can get the normal of the surface we are in contact with. Accordingly, we will know where to push the player away.
Here is a simple player script that can walk right-left-forward-backward and will push off objects with the TagOfEnergyBarrier tag (you can choose any tag and assign it to your Energy Barrier):
using UnityEngine;
public class MovePlayer : MonoBehaviour{
Rigidbody rb;
void Start(){
rb = GetComponent<Rigidbody>();
}
void FixedUpdate(){
var move = transform.position + new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * 0.1f;
rb.MovePosition(move);
}
// that's what you need
private void OnCollisionEnter(Collision collision){
if (collision.gameObject.CompareTag("TagOfEnergyBarrier"))
{
rb.AddForce(collision.GetContact(0).normal * 10, ForceMode.Impulse);
}
}
}
I tried this but it didn't seem to work for me and I've honestly no idea why! The reason for explosion force was that I couldn't find a way to direct the apply force before.
Your answer
Follow this Question
Related Questions
AddExplosionForce only pushing objects in +Y 5 Answers
What does rigidbodies sleeping have to do with collision detection? 0 Answers
RigidBody and collision.contacts 0 Answers
ExplosionForce On Instantiated Object 1 Answer
Animator overriding collisions? 0 Answers