Unity2D:如何使对象向前移动

3

我正在尝试运行一个简单的脚本,在Unity中使一个对象向前移动。

我的代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveToHold : MonoBehaviour {

    private float traveledDistance;
    public int moveSpeed = 10;
    private bool isMoving;
    public GameObject Aircraft;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (isMoving == true)
        {
            //Aircraft.transform.position += transform.forward * Time.deltaTime * moveSpeed;
            Aircraft.transform.position += transform.forward * moveSpeed * Time.deltaTime; 
        }

    }

    public void move ()
    {
        isMoving = true;
        Debug.Log(isMoving);
    }
}

据我所看到的,transform.position 应该有效。有什么想法吗?

你目前看到了什么行为?飞机有移动吗?有出现任何错误吗?你是否已经将一个GameObject分配给“Aircraft”变量?“move()”函数是否被调用并且你是否看到了预期的日志条目? - Junuxx
你的游戏物体上是否有Rigidbody2D组件? - I.B
2个回答

3
尝试更改:

Aircraft.transform.position += transform.forward * moveSpeed * Time.deltaTime;

致:

Aircraft.transform.position += transform.right * moveSpeed * Time.deltaTime;

有时候在使用Unity2D时,前向轴是Z轴,所以你把物体向内推动的是Z轴,这样你是看不到移动效果的。如果想要向右移动,需要在x轴上进行移动。

啊..搞定了!谢谢 :) - user2868524
我该如何让脚本减速?..目前运行时,它只是无限制地快速执行。 - user2868524
如果你只想让它慢一些,可以降低你的moveSpeed变量。 - I.B
啊,伙计。由于某种原因,我在脚本中进行了更改,但检查器中仍然设置为10,所以它仍然会弹出。再次感谢。 - user2868524
@DanielColthart:这是预期的行为。检查器值可以与脚本中的公共实例变量值不同,并且始终会覆盖它们。 - Junuxx
显示剩余2条评论

2

我认为你需要将应用程序应用于RigidBody对象,而不是飞行器。如果我猜得对的话,那应该是你的飞机的父级对象。请尝试以下代码:

Aircraft.parent.transform.position += transform.forward * moveSpeed * Time.deltaTime;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接