- Home /
I need to add a force to an object based on the local vector of the object that is hitting it and not the world coordinates or local coordinates of the object being hit.
I have the following script attached the the "projectile" I thought that the "direction" variable take the vector3 of the owner of the script but it did not. I am a novice and I appreciate any help.`using UnityEngine; using System.Collections;
public class Projectile : MonoBehaviour
{ public float power; private Vector3 direction;
void OnTriggerEnter(Collider other)
{
direction = Vector3.forward;
other.rigidbody.AddRelativeForce(direction * power);
}
}`
Thanks!
Not exactly sure what you want. You are probably looking for:
direction = transform.forward;
other.rigidbody.AddForce(direction * power);
This will add the force based on the forward direction of this object to the object being hit.
Answer by Baste · Nov 11, 2014 at 10:14 AM
Vector3.forward is the global forward (Z-axis, (0,0,1)) Vector. If you want the local forward, you need to use the transform's forward, helpfully named transform.forward.
So your code would be:
void OnTriggerEnter(Collider other)
{
direction = transform.forward;
other.rigidbody.AddRelativeForce(direction * power);
}
@Baste - AddRelativeForce() takes a local coordinate, not a world coordinate.
That doesn't make much sense ;) AddRelativeForce expects a Vector in local space. transform.forward is actually a worldspace vector. Using it like a localspace vector of another object will result in some strange direction. The solution is to not use localspace at all. Use the normal AddForce and use a worldspace vector like transform.forward of the object you want.
Thank you Baste I have used transform.forward as you see below and it works pretty well.
public float power;
public Transform direction;
void OnTriggerEnter(Collider other)
{
Vector3 localForward= power*direction.forward;
other.rigidbody.AddRelativeForce(localForward);
Destroy(gameObject, 1f);
}
}
this way the force goes with the projectile. thanks again.