问题
I am a newbie to Unity, any help will be much appreciated.
I want to make a game where character (shown in below image) moves forward continuously. Character has to move upwards when user touches mobile screen (long touch will make character move upwards continuously), otherwise character falls down slowly due to gravity. Main theme is to avoid touching obstacles and character motion should be curvy. This is a 3D game, but character moves in x,y axis.
Till now, I have written below code to move the character forward and also move character upward when mobile screen touched, but it didn't worked as expected.
In update method:
transform.position += Vector3.right * Time.deltaTime * movementSpeed;
if (Input.touchCount > 0)
{
if (Input.GetTouch (0).phase == TouchPhase.Began)
{
// move player against the gravity
transform.position += Vector3.up * Time.deltaTime * movementSpeed;
}
if (Input.GetTouch (0).phase == TouchPhase.Ended)
{
// gravity acts on the character, so character falls down
}
}
回答1:
You can take a look into one of the Quaternion functions - LookRotation:
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
The code should be as simple as this:
Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
transform.rotation = rotation;
where target.position
is the position where you touch the screen, transform.position
is the position and transform.rotation
is the rotation of your moving object.
Hope this helps :)
来源:https://stackoverflow.com/questions/39141184/how-to-move-character-forward-and-also-face-moving-direction