Unity 5:如何让对象移动到另一个对象?

时间:2015-11-14 05:16:17

标签: c# unity3d

我想知道如何平滑地将一个物体移动到另一个物体,好像我把它扔到另一个物体上。

说我有对象A和对象B.

我想,如果我单击对象B,则对象A将平滑地转到对象B.

我这样做了:

using UnityEngine;
using System.Collections;

public class GreenEnvelope : MonoBehaviour
{
void Start()
{
    if(Input.GetMouseButton(0))
    {
        Update();
    }
}
void Update()
{
    GreenMail();
}

private void GreenMail()
{
    //the speed, in units per second, we want to move towards the target
    float speed = 40;
    float rotateSpeed = 100f;

    //move towards the center of the world (or where ever you like)
    Vector3 targetPosition = new Vector3(-23.77f, -9.719998f, 0);

    Vector3 currentPosition = this.transform.position;
    //first, check to see if we're close enough to the target

        if (Vector3.Distance(currentPosition, targetPosition) > .1f)
        {
            Vector3 directionOfTravel = targetPosition - currentPosition;
            //now normalize the direction, since we only want the direction information
            directionOfTravel.Normalize();
            //scale the movement on each axis by the directionOfTravel vector components

            this.transform.Translate(
                (directionOfTravel.x * speed * Time.deltaTime),
                (directionOfTravel.y * speed * Time.deltaTime),
                (directionOfTravel.z * speed * Time.deltaTime),
                Space.World);
            transform.Rotate(Vector3.up, rotateSpeed * Time.deltaTime);
         }
     }
}

但我必须继续点击该对象以便它移动...我必须一直点击它每个框架...这不是我想要的。我只想点击一次“对象B”,我的“对象A”就会顺利地转到“对象B”

1 个答案:

答案 0 :(得分:0)

1 - Update方法是一种在每一帧中运行的方法。因此,您需要在update方法中检测鼠标单击,然后调用另一种方法,如下所示:

void Start()
{
}

void Update()
{
    if(Input.GetMouseButton(0))
    {
        // Do what ever you want
    }
}

2 - 此移动必须采用Update方法才能顺利运行,为此,您可以使用布尔标志。像这样:

using UnityEngine;
using System.Collections;

public class GreenEnvelope : MonoBehaviour
{
    bool isMove = false;
    float speed = 40;
    Vector3 targetPosition;
    Vector3 currentPosition;
    Vector3 directionOfTravel ;

    void Start()
    {
    }

    void Update()
    {
        if(Input.GetMouseButton(0))
        {
            isMove = true;
        }

        if (isMove == true)
        {
            GreenMail();
        }
    }

    private void GreenMail()
    {
        targetPosition = objB.transform.position; // Get position of object B
        currentPosition = this.transform.position; // Get position of object A
        directionOfTravel = targetPosition - currentPosition;
        if (Vector3.Distance(currentPosition, targetPosition) > .1f)
        {
            this.transform.Translate(
                (directionOfTravel.x * speed * Time.deltaTime),
                (directionOfTravel.y * speed * Time.deltaTime),
                (directionOfTravel.z * speed * Time.deltaTime),
                Space.World);
         }
         else
         {
             isMove = false;
         }
    }
}