I have looked all over and was about to give up, Even when searching the web all that shows up is ‘Rotate sprite to face direction’ which is not what I want.
I have made a Space Game in Game Maker (using the scripting part not the drag and drop stuff) which can do exactly what I want but here its alot different I just want the Ship to move forwards ( which is unity’s case is up ) in what ever direction its facing currently I have this script;
private float inputMovement;
private Vector3 inputRotation;
void Update () {
inputMovement = Input.GetAxis("Vertical");
inputRotation = new Vector3(0,0,-Input.GetAxis("Horizontal"));
transform.Rotate(inputRotation);
rigidbody2D.AddForce (transform.up * inputMovement);
}
which is really basic movement, and works Ok and moves forward in what ever direction its facing but as I’am guessing most of you know that AddForce doesn’t stop the player, while it is nice movement for spaceships I just cant find away for it to stop, either I shall create my own ‘Acceleration’ code if there is another way to move forwards in direction or use a suggestion someone else puts up.
I am really stuck here :?
You can set the rigidbody2D.velocity directly. If you set it to Vector2.zero the object should stop immediately. Is that good enough?
I shall have a look into this, I am rather new to Unity.
I have seen a few examples with velocity but was unsure what it actually does in a 2D space, would it be possible for you to give me an example?
Update:
Just Tried using velocity and i believe this is the way to go, however i am unsure how to make it so it moves ‘forward’ in what direction its facing.
Sure. It does what it says on the tin. It sets the rigidbody’s velocity to whatever you put there, and will continue to move at that velocity unless other forces change it, like collision, drag, or gravity.
Your code snippet can be rewritten as follows:
private const float MaxMovementSpeed = 10.0f; // Or whatever.
private float inputMovement;
private Vector3 inputRotation;
void Update()
{
inputMovement = Input.GetAxis("Vertical");
inputRotation = new Vector3(0,0,-Input.GetAxis("Horizontal"));
transform.Rotate(inputRotation);
}
void FixedUpdate()
{
// Always a good idea to do all physics-related updates in FixedUpdate instead of Update
// Only update the velocity if you need to, or the physics engine might freak out.
var newVelocity = transform.up * inputMovement * MaxMovementSpeed;
if (!Mathf.Approximately(rigidbody2D.velocity.x, newVelocity.x) ||
!Mathf.Approximately(rigidbody2D.velocity.y, newVelocity.y)
{
rigidbody.velocity = newVelocity;
}
}
I wrote this code without checking if it compiles or not, but you should be able to get the gist of it.
HTH
This Works amazingly! why something like this was not already out there I do not know…
I am however not too fussed on collision and i havent fully decided if i want collision in the game well other than bullets hitting things :S
But thanks again 