【发布时间】:2018-09-15 06:45:06
【问题描述】:
我目前有一个关于我正在开发的游戏的脚本,其中将无人机设置为向我的鼠标光标单击的位置移动。
这个将在下面发布的脚本完全可以正常工作,并且运行没有问题。直到我向无人机添加了一个浮动动画,由于动画的变换位置,脚本才停止工作。
现在我进入游戏时没有编译器错误,只是似乎没有响应。
一个重要的因素是我的动画是我的无人机上下移动
这是我的代码:
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class lightDrone : MonoBehaviour
{
public float speed = 2.0f;
// Our destination needs to be remembered outside a single iteration of
// Update. So we put it outside of the method in order to remember it
// across multiple frames.
private Vector3 currentDestination;
// We need to check if we're at the destination yet so we know when to stop.
private bool notAtDestinationYet;
// When we're closer to the destination than this tolerance, we decide that
// we have arrived there.
private float tolerance = 0.1f;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
var newPosition = hit.point;
currentDestination = new Vector3(newPosition.x, 3.0f, newPosition.z);
notAtDestinationYet = true;
}
}
if (notAtDestinationYet)
{
// Use a bit of vector math to get the direction from our current
// position to the destination. The direction is a normalized Vector
// that we can just multiply with our speed to go in that direction
// at that specific speed!
var heading = currentDestination - transform.position;
var distance = heading.magnitude;
var direction = heading / distance;
// Check if we've arrived at our destination.
if (distance < tolerance)
{
notAtDestinationYet = false;
}
else
{
// If the remaining distance between us and the destination is
// smaller than our speed, then we'll go further than necessary!
// This is called overshoot. So we need to make our speed
// smaller than the remaining distance.
// We also multiply by deltaTime to account for the variable
// amount of time that has passed since the last Update() call.
// Without multiplying with the amount of time that has passed
// our object's speed will increase or decrease when the
// framerate changes! We really don't want that.
float currentSpeed = Mathf.Clamp(speed * Time.deltaTime,
Mathf.Epsilon, distance);
transform.position += direction * currentSpeed;
}
}
}
}
显然,我想让这段代码正常工作,如何调整我不断移动的位置以匹配这段代码?我很新,所以像我 5 岁一样解释。谢谢:)
【问题讨论】: