- Home /
The question is answered, right answer was accepted
Moving a object randomly without it being inside a wall
Hello, i am trying to make some types of pickups spawn inside a given area, although some usually get stuck within the walls, how would i fix this?
Code in question for moving objects:
for (int x = 0; x < garbage.Length; x++)
{
if (x < 5)
{
garbage[x].transform.position = new Vector3(Random.Range(-33.0f, 30.0f), 2.35f, Random.Range(30.0f, -35.0f));
}
}
Fixed it. Thanks.
You will need to use a Rigidbody
(and a Collider
), and call $$anonymous$$ovePosition()
on it. $$anonymous$$ovePosition()
detects if the rigidbody would be inside something when moving to that position, and stops the movement at the boundaries.
You can have the Rigidbody
either on the object that you move, or have the object that you show follow an "invisible" object with the Rigidbody
in its LateUpdate()
function.
Answer by tormentoarmagedoom · Jun 04, 2018 at 10:15 AM
Good day.
It's very simple.
You should use colliders to detect if 2 objects are touching or inside eachother. If you detect a collision, then recalculate the position for spawining.
When i use physics.OverlapSphere, it is not returning any value. I must ask, do i need a sphere collider in order to use physics.OverlapSphere
void DetectedObstacle()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, 0.8f, 1 << 10);
if(hitColliders.Length >= 0)
{
Debug.Log("Worked"); // Didn't actually return the log
}
}
No you do not need a collider for Physics.OverlapSphere. Are you sure that your layermask is right? Please try it once without to see if it returns any results. You can also sort throught the results and check if they contain the objects of the layer you want to check against.
Doesn't return nothing after removing layermask
void DetectedObstacle()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, 0.8f);
if (hitColliders.Length == 0)
{
Debug.Log("Clear to Spawn"); Never triggers even when its clear
}
}
EDIT: The pickups itself are triggers, not sure if this helps
Follow this Question
Related Questions
Random instantiate at same frame with each instantiate having unique random direction 1 Answer
Instantiate problem 0 Answers
How can I randomly create a number and then delete it to stop repeating 3 Answers
Help with bombs destroying colliders in different position from gameobject 0 Answers
Why is my Prefab Instantiating when the Scene is Loaded? 2 Answers