Hello, everyone. I need help making a script that allows the enemy to teleport randomly based on the player’s location (cough Slender cough cough). Can anyone who knows how to do this help me out here. If so, it would be greatly appreciated. Please and thank you!
There is a very easy quick way. Make a script (or modify the existing enemy script) and add this line
public GameObject player;
then in the editor drag your player game object onto it.
then in your enemy script you can do things like player.transform.position to get where the player is
then you do your code to determine a new random position
this.transform.position = that new position
A better long term solution is to get an existing GameManager script (or write your own) that handles keep track of where everyone is. Then your enemy would just call the GameManager and ask where the player was.
Well, if you just want it to teleport when the player hits certain points that is a simple:
if (player.transform.position == position) {
enemy.transform.position = randlocationgenerator();
}
Here you would use randlocationgenerator() to create a new Vector3() to assign. Worth noting is that I don’t think you actually use Transform.Position to test for equality, I think you need to test for equality on all three values. If you want to do specific coordinates it might be easier to use a collider, but I have less experience with that.
If you want the enemy to transport at random times then just roll randomly against a chance for whether or not enemy should teleport. Something like:
if (chance > rand.nextdouble % 6) {
enemy.transform.position = randlocationgenerator();
}
Thanks, everyone. I really appreciate it, your advice was very helpful.