- Home /
The question is answered, right answer was accepted
add force in camera direction
I'm using this script to make a crate to be pushed strongly in the direction of my FPS camera:
void Update () {
if(Input.GetButtonDown("fus")){
crate.rigidbody.AddForce(cameraRelativeRight * power);
crate.rigidbody.AddForce(cameraRelativeForward * power);
}
}
when the variables are:
cameraRelativeRight = Camera.main.transform.TransformDirection(Vector3.right);
cameraRelativeForward = Camera.main.transform.TransformDirection(Vector3.forward);
Already tried:
combine the forces in the same term (like this: (cameraRelativeRight+cameraRelativeForward) * power
make it with this variables:
this.cam = Camera.main.transform;
this.cameraRelativeX = cam.TransformDirection(Vector3.right);
this.cameraRelativeZ = cam.TransformDirection(Vector3.forward);
by adding my main camera as "cam"
nothing worked, the crate just pushed wherever it wants...
I want it to go away from the camera by the x and z terms, but it's pushing the same direction all the time
Answer by robertbu · Aug 18, 2013 at 04:52 PM
If you want the crate pushed towards the camera, you need to construct a vector from the crate towards the camera:
Vector3 pushDir = Camera.main.transform.postion - crate.transform.position;
crate.rigidbody.AddForce(pushDir.normalized * power);
Actually I want the exact opposite, but I will try something with this logic
doesn't working, I want it to be pushed away only by the X and Z axises
You said towards the camera. For something opposite reverse the calculation:
Vector3 pushDir = crate.transform.position - Camera.main.transform.postion;
crate.rigidbody.AddForce(pushDir.normalized * power);
Your power variable might be too high. Did you try following the crate in scene view while you play?
so in the end I did the most simple thing, just: crate.rigidbody.AddForce(Camera.main.transform.forward * power);
and it's working like a magic
Nice man! I use crate.rigidbody.AddForce(Camera.main.transform.forward * power);
and it's working like a magic too. But now it is a "forward throw" the object, I want to add a little bit "throw upward" as well. Do you know how to do it? Like throw a basketball, not a base ball.
Follow this Question
Related Questions
Raycasting with Rotation of Camera 0 Answers
Relative AddForce 0 Answers
How to change Add.Force direction depending on the camera angle in the XZ plane 0 Answers
Multiple Cars not working 1 Answer
Release camera 1 Answer