W
W
WasTabon2022-02-13 20:07:48
Unity
WasTabon, 2022-02-13 20:07:48

Movement of a 2d object in the direction it is looking at?

Seriously, I've looked all over the Internet, Vector3.forward , Vector2.up , transform.forward
tried everything, nothing helped

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WasTabon, 2022-02-14
@WasTabon

float moveInputY = Input.GetAxis("Vertical");
        if (moveInputY > 0)
        {
            Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 newPos = Vector2.MoveTowards(rigidbody2D.position, mousePosition, Time.fixedDeltaTime * shipSpeed);
            rigidbody2D.MovePosition(newPos);
        }

I came up with something to code, but the object stupidly moves towards the mouse regardless of the turn, which looks wretched and crooked

T
tvoypsheni4ka, 2022-02-16
@tvoypsheni4ka

The Sprite Renderer component has Flip, which allows you to change the side of the view, you can change it in the code itself,

private SpriteRenderer sprite;
public float speed = 3f;
private bool FacingRight = true; //задаем булевую переменную под сторону, куда будет смотреть объект
private void Awake()
{
   sprite = GetComponentChildren<SpriteRender2D>();
}
private void Update()
{
     float moveInput = Input.GetAxis("Horizontal"); //в Update запишем код для перемещения объекта
     transform.position += new Vector3(moveInput, 0, 0) * speed * Time.deltaTime;
     sprite.flipX = FacingRight < 0 ? true : false;  //Задаем условие при котором будет поворачиваться объект в виде (условие - ?) (действие) (: - иначе) (действие иначе)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question