I’m trying to make a safezone script for my game but I am having difficulties.
I am trying to make it like this →
- If a certain key is pressed and safezone = false, countdown from 10, when the countdown is over set the players x,y,z coords to the safezone object coords
- if a certain key is pressed and safezone = true, select a random number and then set the players x,y,z coords to one of the spawn locations
Can someone help?
#pragma strict
var safeZone : GameObject;
var safeZoneRange = 1000; //Change this depending on how big you want the safe zone to be
var inSafeZone : boolean;
var player : GameObject;
var distance = Vector3.Distance(player.transform.position, safeZone.transform.position);
function Update() {
if (distance <= 1000) {
inSafeZone = true;
} else {
inSafeZone = false;
}
if (Input.GetKeyDown("p")) { //Replace P with the key you want
if (inSafeZone == false) { //If in the wild
TP2SafeZone(); //You use functions if using a timer type thing
} else if (inSafeZone == true) {
var x = Random.Range(1000, 100000); //Replace this numbers with the min and max teleport random
var y = Random.Range(1000, 100000);
var z = Random.Range(1000, 100000);
player.transform.position = Vector3(x, y, z); //This is the random teleport part
}
}
}
function TP2SafeZone() {
if (inSafeZone == false) { //This just double checks so that if you spam the P key it won't repeat this function more than once
yield WaitForSeconds(10);
player.transform.position = Vector3(0, 0, 0); //Replace the 0s if the safe zone is not at the center of the map
}
}
Apply this script to the player and in the inspector assign the safzone and player. For the safe zone just create an empty game object so it is invisible and put it where ever and assign it to the script through the inspector. When making this I didn’t see you wanted it to pick a random number and go to the spawn, so to do that use the var random = Random.Range(1, number of spawns); then do if statements after that like if(random = 1) {player.transform.position = Vector3(235, 585, 993)} etc. and so on. If you need more help with that let me know and I will attach another script. Also this is JavaScript and you are free to copy exactly if you want but you learn things better when typing it out and changing things up.