Why is Collider.IsTouching not working in this sample?
Hey guys, I'm brand new to unity, and figured I'd get to grips with it by tackling the scripting API head on before anything else, but I've come across a bit of a stumbling block.
Here is my script, which is fairly straight forward. It's attached to an empty GameObject that in turn programmatically creates a couple of new GameObects (a green and a red box). The green box follows the mouse cursor around, while the red one sits there in the middle of the scene.
I wanted to test collision, so I added BoxCollider2D components to both objects, but when I compare them using IsTouching, the result is false. I was suscpisious of the bounds not being right, so I performed a manual collision check using the bounds.max and .min vectors, but that returned true... So now I'm very confused. What exactly is IsTouching checking for?? Why does it return false?
Here is my code :
using UnityEngine;
using System.Collections.Generic;
public class Game_Init : MonoBehaviour {
GameObject player_cursor;
List<GameObject> other_stuff;
Game_Init(){
other_stuff = new List<GameObject> ();
}
void Awake(){
player_cursor = new GameObject();
player_cursor.name = "Cursor";
SpriteRenderer cursor_renderer = player_cursor.AddComponent<SpriteRenderer>();
cursor_renderer.sprite = Resources.Load("green_box", typeof(Sprite)) as Sprite;
player_cursor.AddComponent<BoxCollider2D>();
/////////////////////////////////
GameObject random_box = new GameObject();
random_box.name = "random_box";
SpriteRenderer box_renderer = random_box.AddComponent<SpriteRenderer>();
box_renderer.sprite = Resources.Load("test/red_box", typeof(Sprite)) as Sprite;
random_box.transform.localScale = new Vector3 (3, 3, 1);
random_box.transform.position = new Vector3 (0, 0, 0);
random_box.AddComponent<BoxCollider2D>();
other_stuff.Add(random_box);
}
void Update() {
BoxCollider2D collider =
player_cursor.GetComponent (typeof(BoxCollider2D)) as BoxCollider2D;
foreach (GameObject a_stuff in other_stuff) {
//Debug.Log(other_stuff.Count);
BoxCollider2D a_stuff_col =
a_stuff.GetComponent(typeof(BoxCollider2D)) as BoxCollider2D;
if(collider.bounds.max.x > a_stuff_col.bounds.min.x
&& collider.bounds.min.x < a_stuff_col.bounds.max.x
&& collider.bounds.max.y > a_stuff_col.bounds.min.y
&& collider.bounds.min.y < a_stuff_col.bounds.max.y){
Debug.Log("is inside of box " + (new System.Random()).Next(1,10000));
} //worky
if(collider.IsTouching(a_stuff_col)){
Debug.Log("Contact!");
} //no-worky
}
player_cursor.transform.position =
new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y,
0
);
}
}
Your answer
Follow this Question
Related Questions
Collisions not working 0 Answers
Particle System Prefab on collision? 0 Answers
OnCollisionEnter2D not detecting collision 1 Answer
Collision Detection between two different Prefabs doesnt work 1 Answer
New Hierarchy Son Script 0 Answers