- Home /
Set rotation based on where player is facing
Hey guys
So I have a 2D prototype I am testing. I have a working moving and turning ship. My issue however is:
How can I make my ship "continue" to face the direction I moved?
Currently when I move my ship turns into that direction however when I stop moving it resets looking straight ahead.
I don't want that. Any help would be appreciated
Code: Look at the Move() and Turning() functions
public float speed;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private Vector3 movement;
private Rigidbody rb;
private AudioSource audioFire;
private float nextFire;
void Awake ()
{
audioFire = GetComponent<AudioSource>();
rb = GetComponent<Rigidbody>();
}
void Update()
{
if(Input.GetMouseButtonDown(0) && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
audioFire.Play();
}
}
void FixedUpdate ()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Move(h, v);
Turning(h,v);
}
void Move(float h, float v)
{
movement.Set(h, 0.0f, v);
movement = movement.normalized * speed * Time.deltaTime;
rb.MovePosition(transform.position + movement);
}
void Turning(float h, float v)
{
//this makes it rotate and turn towards the direction I am moving
transform.forward = Vector3.Normalize(new Vector3(h, 0f, v));
}
}
Answer by FortisVenaliter · May 11, 2017 at 08:54 PM
You basically need to check that you are receiving input to turn. So, in your Turn function, check that the absolute value of h and v are more than, say, 0.01. If they are, apply the turning, if not, don't and let it stay the same as before.
Okay but how would you make the ship remaining facing in that direction. Say I move left, I would like for my ship to stay looking left when I release the button.
That's literally what I described. Right now it's resetting because you're still setting the rotation when the input is [0,0]
Your answer
Follow this Question
Related Questions
turn fish3d follow mouse 0 Answers
Rotate a ship so cannons can face the objective (another ship) 2 Answers
Unity AI Obstacle Avoidance Help 3 Answers
2D AI: How to get the AI to aim ahead of its target? 3 Answers