- Home /
How to properly make a rocket controller.
I found some code on a youtube video, and after learning some stuff about c# I modified it and got some of it working, the 2 main things I don't think are working are applying thrust where the top of the rocket is pointing after I turn it, and also how to rotate the rocket on the x and z rotation axis. I sorta have this working but when I let go of the key it does not stop rotating, I want it to fall, I just want it to immediately stop rotating when I let go of the key. (I don't want to post a lot of stuff on here so I'm also going to ask 1 more question for something later into the game) It is a 3d game and I want it do something when you touch all four landing legs on the ground. I don't really know how I would do that. Here is my current code.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour
{
public float thrustMultiplier;
public float rotationSpeed;
private bool applyThrust = false;
public Quaternion rotation = Quaternion.identity;
public Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
// Check for misc keypresses
void CheckMiscKeys ()
{
// Start applying thrust
if (Input.GetButtonDown("Jump"))
{
applyThrust = true;
}
if (Input.GetButton("Fire3"))
{
applyThrust = false;
}
}
// Check for rotation keypresses
void CheckRotationKeys ()
{
float turn = Input.GetAxis("Vertical");
if (Input.GetKeyDown(KeyCode.W))
{
rb.AddTorque(transform.forward * rotationSpeed * turn);
}
if (Input.GetKeyDown("s"))
{
rb.AddTorque(-transform.forward * rotationSpeed * turn);
}
if (Input.GetKeyDown("a"))
{
rb.AddTorque(-transform.right * rotationSpeed * turn);
}
if (Input.GetKeyDown("d"))
{
rb.AddTorque(transform.right * rotationSpeed * turn);
}
}
// Apply thrust to the rocket's rigidbody
void ApplyRocketThrust ()
{
if (applyThrust)
{
Vector3 force = transform.up * thrustMultiplier;
GetComponent<Rigidbody>().AddForce(force);
}
}
// Run physics calculations and misc events
void FixedUpdate ()
{
CheckMiscKeys ();
CheckRotationKeys ();
ApplyRocketThrust ();
}
}