cocaine4ik
@cocaine4ik

Почему не изменяется направление движения корабля?

Есть корабль направленный вправо. Есть вектор (thrustDirection) который задает направление корабля. После поворота корабля координаты вектора не меняются и корабль далее летит в направлении заданном в методе Start(). Что я делаю не так?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ship : MonoBehaviour {

    Rigidbody2D rb;
    Vector2 thrustDirection;

    const float ThrustForce = 0.1f;
    const float RotateDegreesPerSecond = 15;

    float radius;



    void Start () {
        rb = GetComponent<Rigidbody2D>();
        // thrustDirection(1, 0) make object to move right (because x positive)
        thrustDirection = new Vector2(1, 0);
        radius = GetComponent<CircleCollider2D>().radius;
    }

    private void Update() {
        // calculate rotation amount and apply rotation 
        float rotationInput = Input.GetAxis("Rotate");
        float rotationAmount = RotateDegreesPerSecond * Time.deltaTime;

        if (rotationInput < 0) {
            rotationAmount *= -1;
            transform.Rotate(Vector3.forward, rotationAmount);
            thrustDirection = thrustDirection + new Vector2(Mathf.Cos(rotationAmount * Mathf.Deg2Rad), Mathf.Sin(rotationAmount * Mathf.Deg2Rad));
        } else if (rotationInput > 0) {
            transform.Rotate(Vector3.forward, rotationAmount);
            thrustDirection = thrustDirection + new Vector2(Mathf.Cos(rotationAmount * Mathf.Deg2Rad), Mathf.Sin(rotationAmount * Mathf.Deg2Rad));
        }
    }
    void FixedUpdate() {
        // move ship using thrust force and direction
        if (Input.GetAxis("Thrust") > 0) {           
            rb.AddForce(thrustDirection * ThrustForce, ForceMode2D.Force);
            
        }

    }
}
  • Вопрос задан
  • 218 просмотров
Пригласить эксперта
Ответы на вопрос 1
@FireGM
Проверьте вот этот участок кода
Mathf.Cos(rotationAmount * Mathf.Deg2Rad)
У вас rotationAmount скорей всего всегда находится между -15 и 15 из-за умножение на Time.deltaTime.
При умножении на Mathf.Deg2Rad, число получается между -0.25 и 0.25, а косинус в таком промежутке всегда положительное число.
Вы создаёте вектор с X > 0.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы