- Home /
Teleport using Random.insideUnitCircle relative to a GameObject's position
Newbie here, trying to learn C#. So I have a GameObject (at the moment a placeholder cube) which, when clicked on, will teleport to a random location within 10 units of itself, on the X and Z axes. Or at least that's the idea. I'm not sure what I'm doing wrong; when I click the object it teleports to a location within the constraints of the unit circle but below one corner of the terrain (which is flattened to 300, but I haven't changed its landscape at all).
Here's my code:
using UnityEngine;
using System.Collections;
public class RandomMovement : MonoBehaviour
{
private Vector3 newPosition;
void OnMouseDown()
{
newPosition = Random.insideUnitCircle * 10;
transform.position = newPosition;
}
}
Ideally the object would also snap to the terrain height at that position (possible using Terrain.SampleHeight?), but my main problem is that the Random.insideUnitCircle function seems to be working in world space, when I'd like to make it move the object to a place relative to itself.
I don't know if that makes sense, but thanks in advance if you can help me out. Like I said, I'm a total newbie to C#, so I apologise if this is a really stupid question, which it almost certainly is.
Answer by robertbu · Jul 25, 2013 at 12:46 PM
'insideUnitCircle' returns values in x and y. You need values change in x and z. In addition you cannot independently change the components of transform.position. That is, you cannot do something like:
transform.position.x += 10;
So to solve your problem, you can use:
void OnMouseDown()
{
newPosition = Random.insideUnitCircle * 10;
newPosition.x += transform.position.x;
newPosition.z = newPosition.y+transform.position.z;
newPosition.y = transform.position.y;
transform.position = newPosition;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613110827im_/https://answers.unity.com/themes/thub/images/avi.jpg)