- Home /
How can I apply force in the direction of the camera when the user presses the mouse
Is there a way to, when the person presses the mouse button, apply force in the direction the camera/ object is facing? I have the adding force part, i just need it for the direction the object is facing.
Answer by duck · Apr 16, 2010 at 04:51 PM
Yes, all GameObjects (including cameras) have a transform component, and on the transform class is a .forward variable which indicates the forward direction of that object as a vector.
So, for the main camera's direction, just use this as the force direction vector:
Camera.main.transform.forward
Or for any other object:
thatObject.transform.forward
Or for the forward direction of the object that the script is on, simply:
transform.forward
Multiply it by whatever you want to control the strength.
As an example, you could place this script onto any object that you would like to be "pushed" when clicked on:
var forceStrength = 50.0; private var applyForce = false;
function OnMouseOver() { if (Input.GetMouseButton(0)) { applyForce = true; } else { applyForce = false; } }
function OnMouseExit() { applyForce = false; }
function FixedUpdate() { if (applyForce) { rigidbody.AddForce(Camera.main.transform.forward * forceStrength); } }
Any gameobject with this script attached (and which has a rigidbody) will be "pushable" with the mouse, and will be pushed in the direction of the camera's forward vector.
would you put that like this?
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.$$anonymous$$ouse0)) {
transform.forward; } }
??
that didn't work. I need it so it always travels the direction it's facing, but not fixed on the Axis.
added example. If this isn't close to what you're looking for, please explain in more detail.
Ah thanks, found a simpler way by adding Constant relative force to the object ins$$anonymous$$d, but i may need this for something else :D
Ben, what would it be if the script was attached to the player character and not the object you click on? (i did ask the question on here, if you need more info you could find it) Thanks.
Your answer
Follow this Question
Related Questions
Adjust camera rotation while looking at a target 1 Answer
Camera Rotation 1 Answer
Move character in direction its facing 1 Answer
Camera Control Help 0 Answers
Camera rotation - button emulation 0 Answers