Unity 5:如何使一个对象移动到另一个对象
本文关键字:一个对象 移动 何使 Unity | 更新日期: 2023-09-27 18:22:02
我想知道如何将一个对象平滑地移动到另一个对象,就像我把它扔到另一对象一样。
假设我有对象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-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;
}
}
}