So i’ve searched for solutions to this weird problem and come up with nothing. I thought i’d ask you all, because i’m sure i’m doing something wrong here.
Basically, i have several 2D gameobjects either moving up or down the screen. They all have colliders, and a script attached to affect behaviour. Below is the excerpt in question.
private Rigidbody2D enemyRigidBody = GetComponent<Rigidbody2D> ();
public Vector2 direction; //set to either Vector2.Up or Down on instantiation
public Vector2 move;
void Update () {
RaycastHit2D hit = Physics2D.Raycast (transform.position, move, 3);
Debug.DrawLine (transform.position, (Vector2)transform.position+move*2, Color.red);
if (hit.collider != null && hit.collider.gameObject != this.gameObject) {
GetComponent<SpriteRenderer> ().color = Color.white;
} else if (hit.collider != null && hit.collider.gameObject == this.gameObject)
GetComponent<SpriteRenderer> ().color = Color.green;
else GetComponent<SpriteRenderer>().color = Color.black;
move.y = direction.y;
move.x = horizontalDeviation/10;
enemyRigidBody.velocity= new Vector2 (move.x * speed, move.y * speed);
On instantiation, the Vector2 “direction” is set to either (0,1) or (0,-1). The conditional statements are set up so that:
- while not detecting another collider, the sprite is black
- while detecting another collider, the sprite is white
- while detecting its own collider, the sprite is green.
Gameobjects with a direction of (0,1) work as intended, remaining black until i move my player object in front of them. However, those moving downwards (0,-1), just stay green. What makes it even weirder is that, if i set the RaycastHit2D parameters to (transform.position, -move, 3), the downward-movers don’t detect themselves, and work just fine in detecting objects behind them.
And yes, i’ve unchecked “Queries Start in Colliders” in Project Settings>Physics 2D.
If anyone could help me i’d be very grateful, as this has had me stumped for a while. And please let me know if you need any more info. Thank you!