A
A
Andrew_Yar2021-05-06 01:21:08
Unity
Andrew_Yar, 2021-05-06 01:21:08

C# Unity. How to override the default "forward" direction for a 2D object?

I am a complete newbie in programming, I need help with my task.
I have a 2D object, it rotates in the (x,y) plane and I use
if(Input.GetKey(KeyCode.UpArrow))
{
transform.position += transform.forward / 10;
}
to move in the forward direction of the object, because this direction should rotate with the object, I hope so. But my 2D object moves along the z-axis if I use transform.position += transform.forward / 10; . I understand that if you orient the object with its "nose" along the Z axis, everything should work out if the object rotates in the X, Z or Y, Z planes. Is there a way to change the forward direction for the object to another axis? The goal is to set the movement of the 2D object in the direction of rotation of the conditional "before", without using the Z axis. Or perhaps there is a way to swap the coordinate axes in the 2D project from X, Y to X, Z? If it helps to change the forward direction. I hope I conveyed my idea correctly :-)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MifanyaRa, 2021-05-06
@Andrew_Yar

In your case it is better to use

if(Input.GetKey(KeyCode.UpArrow))
{
    transform.position += Vector3.up * _speed * Timed.delta;
}

where _speed is an output field in the inspector, the value of which you can conveniently change during the game. likewise to move down
[SerializeField] private float _speed = 10f;
if(Input.GetKey(KeyCode.DownArrow))
{
    transform.position -= Vector3.up * _speed * Timed.delta;
}

and for right and left
if(Input.GetKey(KeyCode.RightArrow))
{
    transform.position += Vector3.right * _speed * Timed.delta;
}
if(Input.GetKey(KeyCode.LeftArrow))
{
    transform.position -= Vector3.right * _speed * Timed.delta;
}

And the fact that you used transform.forward is more suitable for 3D games.
And here's the vector theory for you. I think that everything is well described here for your level https://habr.com/en/post/131931/

A
Andrew_Yar, 2021-05-06
@Andrew_Yar

Thanks for the info, very informative article in the link, but I need some time to figure out what I can use. I want to add that I use the "left" and "right" arrows to rotate around the axis (it turned out to be implemented), and I want to use the "up" for acceleration (in the direction of the turn), "down" for slowing down.
This method doesn't work for me:
if(Input.GetKey(KeyCode.UpArrow))
{
transform.position += Vector3.up * _speed * Timed.delta;
}
But, I can use sin to solve my problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question