- Home /
Why thrust direction o f the ship don't change?
We havea ship looking right. Whe have a vector (thrustDirection) which sets the direction of the ship. After rotating the ship, the coordinates of the vector don't changing and the ship continue fly 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 forece and direction
if (Input.GetAxis("Thrust") > 0) {
rb.AddForce(thrustDirection * ThrustForce, ForceMode2D.Force);
}
}
private void OnBecameInvisible() {
Vector2 position = transform.position;
if (position.x - radius > ScreenUtils.ScreenRight) {
transform.position = new Vector2(ScreenUtils.ScreenLeft, transform.position.y);
}
}
}
You need to normalize the thrustDirection vector otherwise it will keep speeding up every time you rotate.
if (Input.GetAxis("Thrust") > 0) {
rb.AddForce(thrustDirection.normalized * ThrustForce, Force$$anonymous$$ode2D.Force);
}
Thanks, but i have anothe problem. Thrust direction don't change after that:
thrustDirection = thrustDirection + new Vector2($$anonymous$$athf.Cos(rotationAmount * $$anonymous$$athf.Deg2Rad), $$anonymous$$athf.Sin(rotationAmount * $$anonymous$$athf.Deg2Rad));
Why?
You could cache the result of the addition in a new variable and set a breakpoint or Debug.Log it.
Vector2 increment = new Vector2($$anonymous$$athf.Cos(rotationAmount * $$anonymous$$athf.Deg2Rad), $$anonymous$$athf.Sin(rotationAmount * $$anonymous$$athf.Deg2Rad));
//Debug.Log("x: " + increment.x.ToString() + " y:" +increment.y.ToString())
thrustDirection = thrustDirection + increment;
Answer by unity_QXOf8bRP-ftYtA · Mar 21, 2019 at 08:28 AM
Changed "AddForce" to "AddRelativeForce" and stay working good. Thanks for help.
but its not working for me can you please help I too have the same problem the ship is not moving on its direction it keeps moving on to the right