How to move character forward and also face moving direction?

给你一囗甜甜゛ 提交于 2019-12-12 05:04:52

问题


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.rotationis the rotation of your moving object.

Hope this helps :)



来源:https://stackoverflow.com/questions/39141184/how-to-move-character-forward-and-also-face-moving-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!