我正在尝试为鼠标控制的角色移动系统创建一个统一的C#脚本。基本上,像暗黑破坏神这样的游戏如何工作,只需点击游戏世界的某个地方,角色就会移动到那个位置。
我首先尝试使用Vector3.MoveTowards方法,但意识到这完全忽略了碰撞。我现在使用的是characterController组件。我将光线投射到地形以获得Vector3位置并使用它来确定我的运动。
然而,我面临的问题是角色确实向点击的点移动,沿途与物体碰撞并向侧面滑动,直到它再次出现在非碰撞路径上。 raycasthit似乎是准确的。但我的性格不会停止移动!
我甚至在任何移动命令之前添加了一个if子句来检查characters.transform.position是否等于光线投射命中位置。然而这没有做任何事。这是我的代码:
using UnityEngine;
using System.Collections;
public class MouseMoverComponent : MonoBehaviour {
private Vector3 direction;
private Vector3 movement;
private Vector3 destination;
private float velocity = 40f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//doMovement
if(gameObject.transform.position != destination){
GetComponent<CharacterController>().Move(movement);
}
//get raycast position on terrain
if(Input.GetMouseButtonDown(0)){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 300.0f))
{
direction = hit.point - transform.position;
movement = direction.normalized * velocity * Time.deltaTime;
if (movement.magnitude > direction.magnitude) movement = direction;
transform.LookAt(hit.point);
destination = hit.point;
}
}
}
}
答案 0 :(得分:1)
似乎您的运动矢量永远不会更新,您可以尝试这样的事情:
// Update is called once per frame
void Update () {
//doMovement
if(gameObject.transform.position != destination){
direction = hit.point - destination;
movement = direction.normalized * velocity * Time.deltaTime;
GetComponent<CharacterController>().Move(movement);
}
//get raycast position on terrain
if(Input.GetMouseButtonDown(0)){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 300.0f))
{
direction = hit.point - transform.position;
movement = direction.normalized * velocity * Time.deltaTime;
if (movement.magnitude > direction.magnitude) movement = direction;
transform.LookAt(hit.point);
destination = hit.point;
}
}
}