如何使角色向前移动并同时面对移动方向? [英] How to move character forward and also face moving direction?

查看:153
本文介绍了如何使角色向前移动并同时面对移动方向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Unity的新手,我们将不胜感激.

I am a newbie to Unity, any help will be much appreciated.

我想制作一个游戏,角色(如下图所示)连续前进.当用户触摸手机屏幕时,字符必须向上移动(长时间触摸将使字符连续向上移动),否则字符会由于重力而缓慢下降.主要主题是避免触摸障碍物,角色动作应弯曲.这是3D游戏,但角色沿x,y轴移动.

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.

在更新方法中:

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
    }
}

推荐答案

您可以查看四元数函数之一-LookRotation:

You can take a look into one of the Quaternion functions - LookRotation:

https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html

代码应该像这样简单:

Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
transform.rotation = rotation;

,其中target.position是触摸屏幕的位置,transform.position是位置,transform.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.

希望这会有所帮助:)

这篇关于如何使角色向前移动并同时面对移动方向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆