首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >字符不改变方向

字符不改变方向
EN

Stack Overflow用户
提问于 2017-01-04 15:29:46
回答 1查看 35关注 0票数 1

我有一个角色每两秒换一次脸(右或左)。在那两秒之后,速度乘以-1,所以它改变了方向,但是它一直向右(->)。

这是我的密码:

代码语言:javascript
运行
复制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour {

public int speed = 2;

void Start () 
{

    StartCoroutine(Animate ());
}

void Update () 
{
    float auto = Time.deltaTime * speed;
    transform.Translate (auto, 0, 0);
}

IEnumerator Animate()
{
    while (true) {
        yield return new WaitForSeconds (2);
        transform.rotation = Quaternion.LookRotation (Vector3.back);
        speed *= -1;
        yield return new WaitForSeconds (2);
        transform.rotation = Quaternion.LookRotation (Vector3.forward);
        speed *= -1;
    }
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-04 15:33:04

这是因为transform.Translate将物体翻译成局部空间,而不是世界空间。

当您执行以下操作时:

代码语言:javascript
运行
复制
// The object will look at the opposite direction after this line
transform.rotation = Quaternion.LookRotation (Vector3.back);
speed *= -1;

你翻转你的对象,你要求朝相反的方向走。因此,对象将在随后的初始方向上进行转换。

要解决问题,我建议您不要更改speed变量的值。

试着想象自己在同样的情况下:

  1. 向前走
  2. 旋转180°,向后走

最后,你“继续”你的道路在同一方向。

以下是最后一种方法:

代码语言:javascript
运行
复制
IEnumerator Animate()
{
    WaitForSeconds delay = new WaitForSeconds(2) ;
    Quaterion backRotation = Quaternion.LookRotation (Vector3.back) ;
    Quaterion forwardRotation = Quaternion.LookRotation (Vector3.forward) ;
    while (true)
    {
        yield return delay;
        transform.rotation = backRotation;
        yield return delay;
        transform.rotation = forwardRotation;
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41467459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档