- Home /
Stop platforms spawning inside player
I am making a game where you play as a ball bouncing around randomly generated platforms. When one platform becomes invisible a new on will be Instantiated to replace it at a random point within the camera's view. This works but often they end up inside the player, sending them flying off randomly. Is there a way to make sure they do not appear anywhere within the player's collider? This is the code I am using. Also, if anyone knows how to only make them appear on the edge of the camera rectangle opposite the side the previous platform exited on, that would be helpful.
ray1=Camera.main.ViewportPointToRay(Vector3(1,1,0));
ray2=Camera.main.ViewportPointToRay(Vector3(0,0,0));
var hit : RaycastHit;
var hit2 : RaycastHit;
if(Physics.Raycast(ray1,hit)){
maxX=hit.point.x;
minY=hit.point.y;
}
if(Physics.Raycast(ray2,hit2)){
minX=hit2.point.x;
maxY=hit2.point.y;
}
Rand1=Random.Range(minX,maxX);
Rand2=Random.Range(minY,maxY);
var platPos=Vector3(Rand1,Rand2,transform.position.z);
var newPlat=Instantiate(platform,platPos,rot);
Answer by robertbu · Jun 07, 2013 at 07:18 AM
One way is just to repeatedly try until you get a position that works. This code assumes you setup a reference to the player game object called 'player'.
var platPos : Vector3;
do {
Rand1=Random.Range(minX,maxX);
Rand2=Random.Range(minY,maxY);
var platPos=Vector3(Rand1,Rand2,transform.position.z);
} while (Vector3.Distance(platPos, player.transform.position) < some_value);
var newPlat=Instantiate(platform,platPos,rot);
Another way would be to generate a position no closer than some distance to the player:
var platPos : Vector3 = Random.insideUnitCircle;
platPos = player.transform.position + platPos * some_distance;
platPos.z = transform.z;
var newPlat=Instantiate(platform,platPos,rot);
Your answer
Follow this Question
Related Questions
Make sure objects are not instantiated on each other 2 Answers
how to move an object clone to mouse position, i dont understand ? 1 Answer
Find a random location, spawn an object there, do it again. 0 Answers
What would be a good way to not have objects spawn inside one another? 2 Answers
How to prevent objects from interpenetrating eachother ? 1 Answer