How to find the position of player after they press a certain key
I'm trying to create a script for when an npc goes to a location after the player presses a key within a certain range. I've got the first part down which is having the npc know when the player presses the key. But I still couldn't figure out how to get the npc to find where the player was standing when the key was pressed so that they could then move to that location.
I know that I need some kind of variable to store the coordinates of the player but otherwise I've been stumped for a while. ://
Here's what I have so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour{
[SerializeField]
private bool player;
private void Update(){
if (player){
if (Input.GetKeyDown(KeyCode.F)){
player = false;
Debug.Log("Person noticed you!");
}
}
}
private void OnTriggerStay2D(Collider2D other){
if (other.gameObject.tag == "Player"){
player = true;
}
}
private void OnTriggerExit2D(Collider2D other){
if (other.gameObject.tag == "Player"){
player = false;
}
}
}
I'm still fairly new to coding in C# and Unity, so sorry if the solution was obvious ://
Answer by Hellium · Dec 23, 2021 at 07:33 AM
public class Move : MonoBehaviour{
private Transform player;
private bool moveTowardsPlayerLocation;
private void Update(){
if (player != null && Input.GetKeyDown(KeyCode.F)){
moveTowardsPlayerLocation = true;
}
if(moveTowardsPlayerLocation)
{
// Do something like
// transform.position = Vector3.MoveTowards(transform.position, player.position, Time.deltaTime);
}
}
private void OnTriggerStay2D(Collider2D other){
if (other.CompareTag("Player")){
player = other.transform;
}
}
private void OnTriggerExit2D(Collider2D other){
if (other.transform == player){
player = null;
}
}
}
Your answer
Follow this Question
Related Questions
How to make a thrown object land on a certain point e.g a thrown spear landing on its tip 0 Answers
How to make a thrown object land on a certain point e.g a thrown spear landing on its tip 1 Answer
Can't get object to destroy itself on collision. 0 Answers
Variable changed via a function immediately resets to previous value 0 Answers
Beginner needs Help! 1 Answer