- Home /
Flying player Rotates in the left and right direction not forward and back
I'm trying to follow a tutorial on a flying rocket game (where you fly around objects and try not to hit them. The player (A pig) rotates only to its left and right and tilts over. I need it to rotate on the axis that will allow it to rotate foward and back so when the player presses the "Space" bar the character will hover in the right direction. The image entails how the player(pig) falls to its side not rotating the in the right axis. ps: The "A" and "D" Keys are used/pressed for rotating.
using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
/ Vector3 direction = otherObject.position - transform.position; Quaternion toRotation = Quaternion.FromToRotation(transform.up, direction); transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed Time.time);*/
public class takeFlight : MonoBehaviour { AudioSource audiosource;
public Rigidbody rigidBody;
float speed = 100f;
void Start()
{
rigidBody = GetComponent<Rigidbody>();
audiosource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
processInput();
}
private void processInput()
{
if ((Input.GetKey("a")))
{
transform.Rotate(Vector3.forward * speed * Time.deltaTime);
}
else if ((Input.GetKey("d")))
{
transform.Rotate(-Vector3.forward * speed * Time.deltaTime);
}
else if (Input.GetKey("space"))
{
rigidBody.AddRelativeForce(Vector3.up * speed * Time.deltaTime);
}
else
{
}
}
}
Answer by Scribe · Apr 13, 2020 at 12:04 AM
Most likely is that the Vector3.forward is just not correct in your case. At a guess, quite a few models import with a 90degree offset in some direction which you may have fixed by manually rotating your object, however it's quite possible that forward
for your pig isn't the same as the world forward
.
Since I don't know your axis from the screenshot your options are, try a different vector, since up
seems to be correct, probably swap forward
for right
and see if that's better.
other solution would be to work in world space rather than local. Using the 3 arg form of Rotate you can do:
transform.Rotate(Vector3.forward, speed * Time.deltaTime, Space.World);
First arg is the axis to rotate around, second is the amount, 3rd is the space that the supplied axis it relative to.
Hope that helps!