# On key press, spawn a collider where my player is facing?

I'm trying to create an attack mechanic to my player hero in my 2D Tower Defense game. When I press the Q button I want my hero to do an animation and spawn a temporary collider shaped as a cone at where the hero is looking at. If this collider collides with a GameObject called "Stone" it will decrease its hpValue with a script I made. If there is multiple Stones in the cone I want it to only effect one Stone, chosen either by random or/and closest to the hero.

How would I go about doing this and how can I detect the direction of where my hero is facing? This is my movement script:

public float speed;   //Movementspeed

Rigidbody2D rbody;

void Start () {

rbody = GetComponentInChildren<Rigidbody2D> ();
rbody.freezeRotation = true;
}

void FixedUpdate () {

Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

rbody.MovePosition (rbody.position + movement_vector * speed * Time.deltaTime);

}


A picture visualising what I mean:

To determine the cone you should create some variables like AttackLength, FieldOfViewAngke and get enemy component to determine enemy position

lookDirection = enemyPosition - player.transform.position;
lookDirection.y = 0;
attackDirection = Vector3.zero;
float angle = Vector3.Angle(lookDirection, transform.forward);

if (Physics.Raycast(enemyPosition, lookDirection, out hitInfo, AttackLength, layerMask))
{
if (angle <= FieldOFViewAngle * 0.5f)
{
//action
}
}


And instead of spawning collider you can go other way by tagging enemy or stone or whatever like "enemy" and add the check to second if-statement like

&&hitInfo.collider.gameObject.tag == "enemy"


To clarify: Green is player, red-enemy. lookDirection Vector is black, gotten from subtraction of playerPos from enemyPos; Yellow is your filed of view, e.g. 170 degrees; Blue is transform.forward Vector from the player; float angle = angle between Blue and Yellow; to check if the enemy is in the FOV, you check if this angle is less then the half of the FOV

To detect the direction that your player is facing you can use transform.forward as a vector3 value .