- Home /
I need help to make the player go towards where the camera is facing.
Need help making the player go towards where the camera is facing. This is the code i have so far: using UnityEngine; using UnityEngine.UI; using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
public Text countText;
public Text winText;
public GameObject exit;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
if (Input.GetKeyDown("space"))
{
transform.Translate(Vector3.up * 30 * Time.deltaTime, Space.World);
}
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
count = count + 1;
SetCountText();
if (count >= 11)
{
Destroy(exit);
}
}
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
if (count >= 12)
{
winText.text = "You Win!";
}
}
}
what do i put and where?
Answer by hamerilay · Feb 03, 2021 at 02:02 PM
You want to use a raycast and then use NavMeshAgent to go to that point, this is how I did it:
download these files from the official Unity GitHub and import "Assets/NavMeshComponents" to your assets folder.
Make an empty gameObject called "NavMesh" and add the "NavMeshSurface" component, select "Agent Type" and click "Open Agent Settings...", here tweek the settings and if the settings are correct go back to the NavMesh GameObject and click "Bake".
Add the "NavMeshAgent" component to your player and create a new script called "Movement".
At the top of your "Movement" script make sure to be type: "using UnityEngine.AI;"
Add the following code in your "Movement" script:
public float speed; Camera cam; Vector3 oldCamPos; Vector3 targetPosition; public NavMeshAgent agent; private void Update() { if (oldCamPos != cam.transform.position) { oldCamPos = cam.transform.position; Ray ray = cam.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2)); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { agent.SetDestination(hit.point); } } } private void Start() { cam = Camera.main; }
This is how it works:
if (oldCamPos != cam.transform.position)
Here we are checking if the position of the camera has changed,
oldCamPos = cam.transform.position;
Ray ray = cam.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
RaycastHit hit;
Here we are setting the old position to the current position, so we can check if the camera moved later and we are preparing for the raycast
if (Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
Here we are shooting the raycast, we put this in an if statement to check if it hit something. If it hit something we move the agent to the point where the raycast hit.