I am following the Project Boost tutorial and tried to build what I had so far.
However, I found that my rocket was not going up when pressing space.
Below is the rocket script applied to the rocket prefab.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : MonoBehaviour
{
[SerializeField] float ThrustSpeed = 2;
[SerializeField] float RCSSpeed = 1.5f;
Rigidbody rbody;
AudioSource asource;
// Start is called before the first frame update
void Start()
{
rbody = GetComponent<Rigidbody>();
asource = GetComponent<AudioSource>();
}
void OnCollisionEnter(Collision collision) {
switch (collision.gameObject.tag) {
case "Friendly":
print("safe");
break;
case "Fuel":
print("fuel");
break;
default:
print("dead");
break;
}
}
// Update is called once per frame
void Update() {
Thrust();
Rotate(Time.deltaTime);
}
void Thrust() {
if (Input.GetKey(KeyCode.Space)) {
//transform.Translate(Vector3.up * ThrustSpeed * Time.deltaTime * 100);
rbody.AddRelativeForce(Vector3.up * ThrustSpeed);
if (!asource.isPlaying) { //plays thrust sound.
asource.Play();
}
}
if (Input.GetKeyUp(KeyCode.Space)) { //stops thrust sound.
asource.Stop();
}
}
void Rotate(float frameTime) {
frameTime *= 100 * RCSSpeed;
if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)) {
return;
}
if (Input.GetKey(KeyCode.A)) {
rbody.angularVelocity = Vector3.zero;
/*rbody.AddTorque(Vector3.forward);*/
transform.Rotate(Vector3.forward * frameTime);
}
if (Input.GetKey(KeyCode.D)) {
rbody.angularVelocity = Vector3.zero;
transform.Rotate(Vector3.back * frameTime);
}
}
}
After testing I found out that rbody.AddRelativeForce(Vector3.up * ThrustSpeed); is not working.
AddRelativeTorque() from the Rigidbody class also does not work.
However, rbody.angularVelocity = Vector3.zero; appears to be working well.
The thrust sound plays when the space bar is pressed, which means the line after rbody.AddRelativeForce(Vector3.up * ThrustSpeed), asource.Play(), is called and the method works.
If I instead use transform.Translate() to move the rocket up, it would work. But for some reason AddRelativeForce() does nothing.
None of these problems exist in the editor, it’s working perfectly fine in Unity Editor. But in the Windows standalone build version AddRelativeForce() and AddRelativeTorque() doesn’t work.
What could be the reason for this, and is there a fix? Thank you!
Additional Info:
I am using Unity 2020.1.6f1 Personal
Operating System is Windows 10.