How can I apply a force to an object (eg, a rolling ball) in the direction that the camera is facing?

Hi to all,

My player comes up to a point where he enters his vehicle in a tunnel, kind of like a subway system.

If I roll my ball on the first straightaway, the controls are going to react properly. Meaning up:moves forward, down:moves backwards, right:moves right and left:moves left. But as soon as I turn as I hit the first turn and no matter if I have some straightaways further ahead, the ball no longer react to the controls I'm sending him resulting in up:moves left, down:moves right, left:moves forward and right:moves backwards.

I've went through unityAnswer/unityForum but I can't find anything on this. I've tried AddTorque, AddForce

Is there a way of making sure that no matter what trajectory my "subway system" has, that the ball will react correctly to the up, down, left and right key?

Would it be possible to use the coordinates of the camera instead or something like that?

To add a force to the ball in the direction that the camera is pointing, use this:

rigidbody.AddForce( camera.transform.forward * speed );

However, often your camera isn't pointing exactly horizontal in relation to your game, so you may want to remove the tilt angle of your camera before using its direction. Eg, if your camera is looking "across but angled down a bit", you don't want your force to be applied in the down direction at all. You can fix that by zeroing the Y value of the camera's forward transform before using it:

Javascript:

var forceDirection = camera.transform.forward;
forceDirection.y = 0;
rigidbody.AddForce( forceDirection.normalized * speed );

C#:

Vector3 forceDirection = camera.transform.forward;
forceDirection = new Vector3( forceDirection.x, 0, forceDirection.y );
rigidbody.AddForce( forceDirection.normalized * speed );

In order for this to provide you with good gameplay controls, you should make it so that your camera continues to follow the object and rotates according to the object's velocity direction.

Try using

`AddRelativeForce`

Then forward will always be forward in relation to the ball's position, same for left right etc.