Move character forward depending on rotation
I got the ray to tell when it cant move working, I have rotation working, I even have the ray rotating correctly. I just cannot think of how to get the character to move forward by 1 unit in the direction it's facing.
if (Input.anyKeyDown)
{
var FowardRayDistance = 0f;
Vector2 fwd = transform.TransformDirection(Vector2.up);
Vector2 bwd = transform.TransformDirection(Vector2.down);
//Foward Ray
while (FowardRayDistance < maxFowardCheckDistance)
{
RaycastHit2D FHit = Physics2D.Raycast(transform.position, fwd, FowardRayDistance);
RaycastHit2D hit = Physics2D.Raycast(transform.position, bwd, FowardRayDistance);
if (FHit)
{
if (Input.GetKeyDown(KeyCode.W) && FowardRayDistance > 1)
{
}
else if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("hit: " + FHit.collider.name + "| at: " + FowardRayDistance);
}
FowardRayDistance = maxFowardCheckDistance;
}
else
{
FowardRayDistance += 1f;
}
}
}
The if (Input.GetKeyDown(KeyCode.W) && FowardRayDistance > 1)
area is where i know the movement part will go i just dont know what to put there.
Answer by streeetwalker · Sep 20, 2020 at 05:06 AM
@LordBitcube, you want to move in specific direction, just multiply the direction by the distance you want to move (in your case 1 Unity unit? Then no need to even multiply) and add it to your current position.
it looks like you have already calculated forward, and assuming your not working with a Rigidbody, then: transform.position = transform.position + fwd
Answer by LordBitcube · Sep 20, 2020 at 07:13 AM
I am quite confused on how that works but it does. I suppose Unity just assumes when adding position forward just add by one by default.
Works perfectly though thank you so much :)
the intuitive explanation is in understanding Vector $$anonymous$$athematics. The forward vector is a vector of magnitude 1. Lets simplify by using 2 Dimensions.
Say your forward direction is a 45 degree angle counter-clockwise from the positive x axis. So the forward vector is: 0.707, 0.707 (if you do the math this is vector of length 1.)
Now say you are at position 1, 5 - $$anonymous$$oving forward by one, the equation is: ( 1, 5 ) + ( 0.707, 0.707 ) = ( 1.707, 5.707 )
Your new position is a distance of 1 from your original position, in the direction you were facing.
Understanding vector mathematics will go a long way to help you understand what is going on. I suggest you watch quite a few videos on the topic.