- Home /
How to smoothly rotate to certain directions using input axis
Kind of a big question here.
I have a space ship. I want it to face different directions based on the arrow keys/wasd. I don't mean look straight to the left or straight up, but on an angle. So if my ship is facing forward and I press up, the ship would loop up at a 45 degree angle and straight when I let go.
That would seem kinda simple, but I need it to work for up down left right as well as when you hold down left and up and so on so forth. I tried creating 8 empty objects around the ship and using look at to determine where the ship is facing, but it just flips out and goes crazy.
There has to be a better way. I have a hard time grasping unity rotation, but what I basically need is to store 8 different rotations for an object and smoothly switch between them depending on what buttons I'm pressing.
Any help would be awesome.
Edit: I'm using C#
Answer by robertbu · Nov 25, 2013 at 06:34 AM
If you have the the "Horizontal" and "Vertical" axes setup in their default configuration, you can get the rotation you are looking for with just a few lines of code:
#pragma strict
var speed = 5.0;
function Update () {
var v3 = Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 1.0);
var qTo = Quaternion.LookRotation(v3);
transform.rotation = Quaternion.Slerp(transform.rotation, qTo, speed * Time.deltaTime);
}
Awesome, I get what it means, but is there any chance you might know what this is in C#?
Untested C# conversion:
using UnityEngine;
using System.Collections;
public class $$anonymous$$yClass : $$anonymous$$onoBehaviour {
public float speed = 5.0f;
void Update () {
Vector3 v3 = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 1.0f);
Quaternion qTo = Quaternion.LookRotation(v3);
transform.rotation = Quaternion.Slerp(transform.rotation, qTo, speed * Time.deltaTime);
}
}
Your answer
Follow this Question
Related Questions
Instantiate GameObject towards player 0 Answers
Transform a Vector by a Quaternion 1 Answer
Unity Quaternion Problem (Should be A Bug?) 1 Answer
Make a side of an object LookAT another object 1 Answer
Need to check transform.rotation 1 Answer