- Home /
Add force relative to the angle/direction?
So I'm trying to make this space exploration game, but I'm having a little trouble getting the force applied to the right direction that the ship is facing. Here is my current code for the movement
     var speed = 0.8;
 
 var turnSpeed = 0.15;
 
 
 
 
 
 function Start () {
 
 
 
     rigidbody.useGravity = false;
 
 }
 
 
 
 function Update () {
 
 var currentvertical : Vector3 = transform.TransformDirection(transform.up*Input.GetAxis("Vertical")*turnSpeed);
 
 var currenthorizontal : Vector3 = transform.TransformDirection(transform.right*Input.GetAxis("Horizontal")*turnSpeed);
 
     if (Input.GetButton("Jump")) { //Spacebar by default will make it move forward
 
        rigidbody.AddRelativeForce (Vector3.forward*speed);
 
     }
 
     rigidbody.AddRelativeTorque(currenthorizontal);
 
     // W key or the up arrow to turn upwards, S or the down arrow to turn downwards.
 
     rigidbody.AddRelativeTorque(currentvertical);
 
     // A or left arrow to turn left, D or right arrow to turn right. 
 
     }
When I try to move, I only move upwards, help with this would be great, thanks.
Answer by aldonaletto · Oct 26, 2011 at 12:26 PM
You're messing the directions using 3 world to local successive conversions and using the wrong axes. If you add a relative torque, you must pass the world axis. To turn left or right in a 3D world, for instance, you must use AddRelativeTorque(Vector3.up  Input.GetAxis("Horizontal")  turnSpeed) - the torque is applied around the axis selected - Y, in this case. Since it's relative, the local Y (up) axis is used.
 The behaviour will be very similar to the RCS (Reaction Control System) that controls a Space Shuttle direction: turning left or right activates the lateral thrusters, and the spaceship starts spinning around its vertical axis.
var speed = 0.8; var turnSpeed = 0.15;
function Start () { rigidbody.useGravity = false; }
function Update () {
 var currentvertical : Vector3 = Vector3.right*Input.GetAxis("Vertical")*turnSpeed;
 var currenthorizontal : Vector3 = Vector3.up*Input.GetAxis("Horizontal")*turnSpeed;
 if (Input.GetButton("Jump")) { //Spacebar by default will make it move forward
    rigidbody.AddRelativeForce (Vector3.forward*speed);
 }
 rigidbody.AddRelativeTorque(currenthorizontal);
 // W key or the up arrow to turn upwards, S or the down arrow to turn downwards.
 rigidbody.AddRelativeTorque(currentvertical);
 // A or left arrow to turn left, D or right arrow to turn right. 
}
Your answer
 
 
             Follow this Question
Related Questions
Adding Forces. Making It Move Strangely. 0 Answers
Relative position? 1 Answer
Relative force 1 Answer
Problem with moving player relative to camera 1 Answer
How to fix/clamp rigidbody dir vector, despite Force dir 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                