- Home /
How do I make a 2D object face the direction it is moving in top down space shooter
I am very new to unity and have no clue how to make this work, I've been working on it for hours. Here is what I have so far:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerController : MonoBehaviour {
private Rigidbody2D body;
public float speed;
private int count;
public Text counttext;
public Text WinText;
void Start()
{
body = GetComponent<Rigidbody2D> ();
count = 0;
WinText.text = "";
SetCountText ();
}
void FixedUpdate()
{
Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical")) * speed;
body.AddForce (moveVec);
}
Answer by villevli · Aug 23, 2016 at 09:15 AM
Add this to your FixedUpdate:
void FixedUpdate()
{
Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"), CrossPlatformInputManager.GetAxis("Vertical")) * speed;
body.AddForce (moveVec);
if (moveVec != Vector2.zero) {
transform.rotation = Quaternion.LookRotation(moveVec, Vector3.back);
}
}
Vector3.back is likely your upwards direction (towards the camera). If not, then change that accordingly.
If you want smoother rotation, use:
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveVec, Vector3.back), Time.fixedDeltaTime * turnSpeed);
The ship rotates on the y and x axis but not the z. I need it to rotate on only the z. As it is now it just disappears.
Try:
transform.rotation = Quaternion.LookRotation(Vector3.forward, moveVec)
The code I posted assumes that the player object's forward axis (blue) points to the direction the player is looking. When using sprites in 2D game, by default it points directly away from the camera when it should point either up or right (x or y) in this top down shooter game. Using that alternative may fix this. (the green axis points where the player is moving / is the forward direction)
@villevli Now the top of my character (ant) faces forward, ins$$anonymous$$d of his front facing forward.
private Vector3 calculateVelocity(){
return antPos.position - previousPos;
}
void updateDirection(){
//Debug.Log(antPos.rotation.ToString ());
//Debug.Log ("Velocity: " + velocity);
//antPos.up = velocity;
Vector3 velocity = calculateVelocity();
Debug.Log("calculated velocity: " + velocity);
antPos.rotation = Quaternion.LookRotation (velocity, Vector3.back);
}
$$anonymous$$y character (ant) disappears when it is moving now.