Reputation:
I am rather new to Unity and C# and have been struggling to figure this out!
I want my ship to gradually gain speed and then slowly stop as if there was no gravity as its going to be a space game!
If anybody could help me or even direct me to a tutorial on this subject i will be grateful! :)
Here is my code for my spaceship currently...
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerMovement : MonoBehaviour {
public float maxSpeed = 6f;
public float rotSpeed = 180f;
void Start ()
{
}
void Update () {
Quaternion rot = transform.rotation;
float z = rot.eulerAngles.z;
z -= CrossPlatformInputManager.GetAxis ("Horizontal") * rotSpeed * Time.deltaTime;
rot = Quaternion.Euler (0, 0, z);
transform.rotation = rot;
Vector3 pos = transform.position;
Vector3 velocity = new Vector3 (0, CrossPlatformInputManager.GetAxis("Vertical") * maxSpeed * Time.deltaTime, 0);
pos += rot * velocity;
transform.position = pos;
}
}
How can this be done?
Upvotes: 1
Views: 7870
Reputation: 296
You can try this:
Vector3 velocity = transform.forward * CrossPlatformInputManager.GetAxis("Vertical") * maxSpeed * Time.deltaTime;
pos += velocity;
transform.position = pos;
I hope its useful.
Upvotes: 0
Reputation: 624
As with anything in Unity, there are a hundred ways you could potentially do this, but i think using physics would be the easiest.
Right now you are directly manipulating the transform. This is fine, but is actually much more complex than just letting Unitys physics do the maths for you.
All you would need to do is attach a Rigidbody component (or Rigidbody2D for a 2D game) to your ship.
Then, by adding force to the Rigidbody, you would get a nice gradual acceleration, and by tweaking the Rigidbodys linear and angular drag in the inspector, you would get a very smooth and natural feeling deceleration.
Here is the official documentation on using physics: https://docs.unity3d.com/Manual/class-Rigidbody.html
Utilising physics is a very fun and important part of Unity development, so if you are just starting out I highly recommend learning it now, and this is the perfect problem to solve with it.
Upvotes: 1