- Home /
How can I raycast the direction my 2D character is facing?
Hello,
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), Color.green);
}
}
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?
Answer by robertbu · Feb 08, 2014 at 07:44 AM
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);
Yeah that will only cast it to the right of the character. Since it's topdown and I can move in any direction, my character can be "facing" left, right, up, or down.
The current code I have allows you to cast in the current direction your moving, but you can only cast in that direction while you're moving.
So the x and y variables are getting the direction and the vector will cast in that direction. So (0,1),(1,0),(1,1),etc. But the thing with using Input.GetAxis is that when you stop moving everything returns to (0,0) and it won't cast in any direction.
I'm asking if there's any way I can either store you previous direction when you stop moving, or have a workaround to the coordinate direction system.
If the only information about direction comes from the Input.GetAxis(), you can handle things this way:
Vector3 previousGood = Vector3.zero;
void meleeAttack()
{
if(Input.Get$$anonymous$$ouseButtonDown (0)) {
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis ("Vertical");
Vector3 dir = new Vector2(x,y);
if (dir == Vector3.zero)
{
dir = previousGood;
}
else
{
previousGood = dir;
}
foundHit = Physics2D.Raycast(transform.position, dir, dist, 1<<8);
Debug.DrawRay(transform.position, , Color.green);
}
}
Your answer
Follow this Question
Related Questions
Hop from transform to transform in 2D game? 0 Answers
Ray Casting in 2D 1 Answer
Raycast direction problem 3 Answers
How do I rotate arround an object by swiping left or right? 0 Answers
How to rotate object to cursor? 1 Answer