К нему прикреплен FPSController
: RigidBody
, Animator
, NavMeshAgent
и два скрипта: PlayerController
и AgentController
.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
float translatioin = Input.GetAxis("Vertical") * speed;
float straffe = Input.GetAxis("Horizontal") * speed;
translatioin *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translatioin);
if (Input.GetKeyDown("escape"))
Cursor.lockState = CursorLockMode.None;
}
}
А также
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AgentController : MonoBehaviour
{
public Camera camera;
public NavMeshAgent agent;
public bool agentControl = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0) && agentControl == true)
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
}
}
}
С PlayerController
я могу перемещаться, используя клавиши WSAD, а с AgentController
я могу щелкнуть в какой-нибудь точке на местности, и агент подойдет туда.
Когда я нажимаю, например, на один из больших кубиков, игрок проходит по нему и останавливается возле него. Но затем, когда я использую клавиши WSAD, чтобы отойти от куба, игрок продолжит автоматически возвращаться к кубу.
Как магнит, который заставляет игрока двигаться к кубу в ту же точку, на которую я нажимал раньше.
На FPSCamera
у меня есть сценарий: просто чтобы с помощью мыши осмотреться.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camMouseLook : MonoBehaviour
{
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
GameObject character;
// Use this for initialization
void Start ()
{
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update ()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, Vector3.up);
}
}
Я обнаружил, что пока игра запущена, если я сниму флажок NavMeshAgent
, я снова смогу нормально ходить с клавишами, но когда NavMeshAgent
включен и я нажимаю на какой-то куб, он будет продолжать двигаться к этому кубу, даже если я перемещение с ключами в другие места.
Я хочу иметь возможность использовать AgentController
и / или PlayerController
, когда игра запущена.
ОБНОВИТЬ:
Я пробовал использовать OnCollisionEnter и OnCollisionExit. Но как только я снова установил значение false для OnCollisionExit, у меня возникла та же проблема. Причина в том, что я снова установил перемещение в значение true в OnCollisionExit, чтобы иметь возможность щелкнуть мышью и снова двигаться.
Так что я снова застрял.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AgentController : MonoBehaviour
{
public Camera camera;
public NavMeshAgent agent;
public bool move = true;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0) && move == true)
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "HitPoint")
{
move = false;
}
}
private void OnCollisionExit(Collision collision)
{
move = true;
}
}