- Home /
Need help with scripting (problem related to rigidbody/velocity)
Hello guys. Im making a 3D space ship game and i got a problem. Here's a piece of my code: Code:
velX+=Input.GetAxis("Horizontal")*sensStrafe;
if (Input.GetAxis("Horizontal")) { rigidbody.AddRelativeForce(velX,0,0); rigidbody.velocity=Vector3(Mathf.Clamp(rigidbody.velocity.x,-maxStrafe,maxStrafe),rigidbody.velocity.y,rigidbody.velocity.z); velXdir=0; } else { if (Mathf.Abs(rigidbody.velocity.x)>=0){ if (velXdir==0) { velXdir=velX/(Mathf.Abs(velX)); } rigidbody.AddRelativeForce(-1*stabStrafe*velXdir,0,0); velX=0; } }
Im moving my ship in horizontal axis using W and S keys. I want to make an inverted force that will appear right after the strafe engines are turned off to stabilise the ship. Variables i used and their purpose: velX - obvious sensStrafe - equals 1 atm. velXdir - equals velXdir/abs(velXdir). I used that to get the dirrection of the stabilisation force. stabStrafe - strafing speed, equals 0.5
Currently my ship got a fixed rotation and the only thing affecting it's transform is the velX.
Problems i get: 1. When im using velXdir in the rigidbody.AddRelativeForce(-1*stabStrafe*velXdir,0,0); im getting an error saying that the force i apply is (n/a,0,0) which means its absent as i understand it. The ship keeps strafing in the original dirrection. 2. When i dont use velXdir and just put rigidbody.AddRelativeForce(-1*stabStrafe,0,0); i get another error. Since this force is applied from the fixed side, i made my ship strafe right so the stabilisation force will occure from right to left. In fact it does occure but the problem is that the stabilisation force just makes the ship endlessly strafe to the opposite direction. As i understand, it means that the if (Mathf.Abs(rigidbody.velocity.x)>=0) isnt getting the "true" value which is a mystery for me.
Can anyone help me?