Hi,
i am working on this game for a while now, and i have one big problem with 2D Triggers. So, let me explain how my trigger should work : i have a block-based game. In the front of the player, there is 2D Trigger that activates when block (with collider) is inside the trigger. When block enters in that area, block changes color to red, and the collider of that block is stored inside variable (for calling functions like “Mine”) and variable isBlockSelected changes it’s value to true. The only problem here is that, if player rotates (it rotates instantly to desired side) trigger don’t return block that is selected after rotating, so the player needs to rotate somewhere where blocks don’t exist, and then return to desired block. I tried to do this with Arrays, and it was good but arrays don’t have Clear method,so i can’t work with them. I also used List, but same problem existed.
Here is the picture:
As you can see, it works, but if player rotates to block on the left side of the player (for us, it’s block above player), it won’t be selected:
(Arrow is the direction of the player)
Code for trigger:
using UnityEngine;
using System.Collections;
public class BlocksController : MonoBehaviour {
//Cooldowns for minning
private float nextAttack;
public float coolDown;
//Selected object
Collider2D selectedBlock;
bool isBlockSelected;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space) && nextAttack <= Time.time)
{
if (isBlockSelected)
{
selectedBlock.SendMessageUpwards("Mine", 1);
nextAttack = Time.time + coolDown;
Debug.Log("Minning!");
}
else print("No blocks selected!");
}
if(Input.GetKey(KeyCode.Space) && nextAttack <= Time.time)
{
if (isBlockSelected)
{
selectedBlock.SendMessageUpwards("Mine", 1);
nextAttack = Time.time + coolDown;
Debug.Log("Minning!");
}
else print("No block selected!");
}
if (Input.GetKeyDown(KeyCode.KeypadEnter))
{
if (isBlockSelected) print("Only one block! " + selectedBlock.name);
else print("No blocks selected!");
}
}
void OnTriggerExit2D(Collider2D other)
{
other.GetComponent<SpriteRenderer>().material.SetColor("_Color", Color.white);
isBlockSelected = false;
selectedBlock = null;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!isBlockSelected)
{
selectedBlock = other;
isBlockSelected = true;
other.GetComponent<SpriteRenderer>().material.SetColor("_Color", Color.red);
}
}
}
P.S. - English is not my native language, so sorry for any mistakes.