- Home /
Detect and Recursively Space Out Platforms in 2D Endless Runner
My goal is to spawn a bunch of different platform prefabs with the tag "Platform", and have them spaced out just after spawn(assuming one spawns on top of another prefab) The prefabs have an edge collider to walk on, a 2d box collider to push them away if they hit the sides of the platform, and another box collider surrounding the entire object that's used as a trigger to set off the movement:
using UnityEngine;
using System.Collections;
public class PlatformCollisionHandler : MonoBehaviour {
BoxCollider2D _thisBox;
void Awake()
{
_thisBox = this.GetComponent<BoxCollider2D>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Platform")
{
movePlatform(other.gameObject);
}
}
void movePlatform(GameObject thePlatform)
{
if (_thisBox.IsTouching(thePlatform.gameObject.GetComponent<BoxCollider2D>()))
{
this.GetComponent<Transform>().position = this.GetComponent<Transform>().position + new Vector3(1f, 0, 0);
movePlatform(thePlatform);
}
else
{
return;
}
}
}
My problem is, when I go to debug, the platforms are still spawning on top of each other and only the if statement is reached
Answer by FortisVenaliter · May 06, 2016 at 07:01 PM
Check out the code reference for the IsTouching function. It says:
It is important to understand that checking if colliders are touching or not is performed against the last physics system update i.e. the state of touching colliders at that time. If you have just added a new Collider2D or have moved a Collider2D but a physics update has not yet taken place then the colliders will not be shown as touching. The touching state is identical to that indicated by the physics collision or trigger callbacks.
Your answer
Follow this Question
Related Questions
Prevent collision between prefab clones on a 2d mode? 0 Answers
Player's speed after collision problem 1 Answer
Link GUIText to a prefab? 2 Answers
Multiple Doors and Buttons 0 Answers