How can I raycast the direction my 2D character is facing?


I am making a top down 2D game in unity, and I’m using a ray cast in the direction my character is facing in order to detect melee hits on enemies.

Right now I have this:

void meleeAttack()
		if(Input.GetMouseButtonDown (0)) {
			float x = Input.GetAxis("Horizontal");
			float y = Input.GetAxis ("Vertical");

			foundHit = Physics2D.Raycast(transform.position, new Vector2(x,y), dist, 1<<8);
			Debug.DrawRay(transform.position, new Vector2(x,y),;

I figured I could use the horizontal and vertical axis from the input in order to determine the direction my character is facing in. This worked perfectly except I need to be moving for this to work.

Is there any way that I can store the previous values from the x and y axis so that it will cast in the last direction when you stop moving? Or is there some kind of workaround to this?

Typically with a 2D sprite either the right side or the up side is the forward. So you can use either transform.right or transform.up of the character in your Raycast(). Assuming this script is on the character and ‘front’ is to the right:

foundHit = Physics2D.Raycast(transform.position, transform.right, dist, 1<<8);