A
A
Alex2019-03-17 16:48:08
C++ / C#
Alex, 2019-03-17 16:48:08

Why doesn't the ship's direction change?

There is a ship pointing to the right. There is a vector (thrustDirection) that specifies the direction of the ship. After the ship turns, the vector coordinates do not change and the ship flies further in the direction specified in the Start() method. What am I doing wrong?

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);
            
        }

    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2019-03-24
@FireGM

Check out this piece of code
. Your rotationAmount is most likely always between -15 and 15 due to the multiplication by Time.deltaTime.
When multiplied by Mathf.Deg2Rad, the number is between -0.25 and 0.25, and the cosine in this range is always a positive number.
You are creating a vector with X > 0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question