- Home /
Question by
emielschumacher · Dec 02, 2017 at 09:02 AM ·
teleportrange
How to teleport near player in range
I make a game where an enemy can teleport to the player. I do this with this code for the teleport:
transform.position = new Vector2 (player.transform.position.x + Random.Range(-3f, -3f), player.transform.position.y + Random.Range(-3f, -3f));
But now the enemy can teleport too near the player. How can I say that he must teleport outside a range of 2 float near the player?
Comment
Best Answer
Answer by Hellium · Dec 02, 2017 at 01:28 PM
Try this :
float maxRadius = 3 ;
float minRadius = 2 ;
Vector2 randomPosition = Random.insideUnitCircle * (maxRadius - minRadius);
transform.position = player.transform.position + randomPosition.normalized * minRadius + randomPosition ;
Answer by Yeezyy · Dec 02, 2017 at 01:52 PM
using UnityEngine; using System.Collections;
public class Teleport : MonoBehaviour { [SerializeField] Transform target; Vector3 dir; Vector3 teleportPos; [SerializeField] float distanceAway; // Use this for initialization void Start() {
dir = Quaternion.Euler(0, Random.Range(0, 360), 0) * target.forward ;
}
// Update is called once per frame
void Update()
{
transform.position = target.position + (dir * distanceAway);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612143812im_/https://answers.unity.com/themes/thub/images/avi.jpg)