简体   繁体   中英

Unity2D: How to get object to move forward

I am trying to run a simple script to get an object to move forward within unity.

My code is:

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

As far as I can see, the transform.position should work.

Any ideas?

Try changing :

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

to :

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

Sometimes with unity2D the forward axis is the Z so you're pushing it inside the Z axis which you won't see. Right will move it on the x axis.

I think you need to apply your position to the RigidBody object rather than the aircraft. If I'm guessing right, that should be your aircraft's parent. Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM