Eroor计算器试图移动使用鼠标右键点击
问题描述:
黑家伙,我必须做出使刚体球移动刚体球当我点击鼠标右键点击时。 **我得到了一个大问题,程序*,我不知道如何使它运行良好。也许问题是因为我打电话递归我的方法,但我真的没有任何其他ideea **Eroor计算器试图移动使用鼠标右键点击
还有就是我在我的剧本确实到现在为止:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Bundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
[Range(1, 20)]
private float speed;
private Vector3 targetPosition;
private bool isMoving;
public Rigidbody rigidBody;
public Bundary bundary;
const int RIGHT_MOUSE_BUTTON = 1;
private void Start()
{
targetPosition = transform.position;
isMoving = false;
}
/// <summary>
/// Sets the travel position where we will travel
/// </summary>
void SetTargetPosition()
{
Plane plane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float point = 0f;
if (plane.Raycast(ray, out point))
targetPosition = ray.GetPoint(point);
//set the ball to move
isMoving = true;
}
void FixedUpdate()
{
transform.LookAt(targetPosition);
Vector3 movement = new Vector3(Input.mousePosition.x, 0.0f, Input.mousePosition.z); //how much we want to move
rigidBody.velocity = movement * speed; //because movement return a value bettwen (0,1) we want the ball move faster so multiply it with our speed
rigidBody.position = new Vector3
(Mathf.Clamp(rigidBody.position.x, bundary.xMin, bundary.xMax), //set x limits with Clamp method
0.0f, //we don't want to move it on Y axex
Mathf.Clamp(rigidBody.position.z, bundary.zMin, bundary.zMax)); //set y limits with Clamp method
//if we are in the target position ,then stop moving !
if (movement == targetPosition)
isMoving = false;
//if the player clicked on the screen , found out where
if (Input.GetMouseButton(RIGHT_MOUSE_BUTTON))
SetTargetPosition();
//if we are still moving ,then move the player
if (isMoving)
FixedUpdate();
}
}
还有就是我的计划应该在最后阶段做的:http://prntscr.com/fqu98u
答
你的问题是双重的。
- 为到达目的地 不准确的测试
- 你的方法不应该是递归
你得到一个堆栈溢出错误,因为在FixedUpdate你的递归代码不正确地终止当你的对象正在移动。在你的情况下,isMoving设置为false,一旦达到目标目的地。可悲的是,你测试确定点是否到达不太可能发生由于浮点,你正在测试的确切坐标。你最好在测试目标的虚拟球体内进行测试。
当写递归代码,你需要确保的条件存在,将终止通话。你的不是。每次调用时,当前的程序计数器被压入堆栈。该堆栈是有限的资源,其耗尽导致堆栈溢出。
通常你会解决它,但因为FixedUpdate是由Unity叫,你应该完全删除递归性,并让该方法被调用随着时间的推移。
你忘了提到这个问题。 – Programmer
我得到了一个大问题,程序*,我不知道如何使它运行fine.i写它,仔细阅读 –
如果你得到一个错误应该发布错误。此外,请通过双击该错误告诉我们导致该错误的代码行。这是一个自上而下还是侧视游戏? – Programmer