- Home /
Making Top-Down spaceship movement, getting current speed, acceleration, without rigidbody!
So I have a simple movement script. My ship rotates on "A and D" and geting maximum speed with"W/S". But, I need so my ship gets to maximum speed not instantly, and wont stop instantly. The thing is, I dont want to use RigidBody2d. My thinkin is : 1) I need somehow get current ship speed, 2) move it with this speed every frame 3) add speed when buttun pressed 4) slowly decrease speed, when nothing pressed
Can someone help whith this? (Sorry for language)
using UnityEngine; using System.Collections;
public class PlayerMovement2 : MonoBehaviour {
public float maxVerticalSpeed;
public float maxRotationSpeed;
public float Speed;
void Start () {
}
void FixedUpdate () {
transform.Translate (new Vector3 (0, Input.GetAxis ("Vertical") * maxVerticalSpeed * Time.deltaTime));
transform.Rotate (new Vector3 (0, 0, -1 * Input.GetAxis("Horizontal") * maxRotationSpeed * Time.deltaTime));
}
}
Answer by villevli · Nov 27, 2017 at 12:22 AM
Here's a simple script which accelerates the object with input and drag is applied each FixedUpdate to slow the object down.
public class ControlledRigidbody2D : MonoBehaviour
{
public float verticalInputAcceleration = 1;
public float horizontalInputAcceleration = 20;
public float maxSpeed = 10;
public float maxRotationSpeed = 100;
public float velocityDrag = 1;
public float rotationDrag = 1;
private Vector3 velocity;
private float zRotationVelocity;
private void Update()
{
// apply forward input
Vector3 acceleration = Input.GetAxis("Vertical") * verticalInputAcceleration * transform.up;
velocity += acceleration * Time.deltaTime;
// apply turn input
float zTurnAcceleration = -1 * Input.GetAxis("Horizontal") * horizontalInputAcceleration;
zRotationVelocity += zTurnAcceleration * Time.deltaTime;
}
private void FixedUpdate()
{
// apply velocity drag
velocity = velocity * (1 - Time.deltaTime * velocityDrag);
// clamp to maxSpeed
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
// apply rotation drag
zRotationVelocity = zRotationVelocity * (1 - Time.deltaTime * rotationDrag);
// clamp to maxRotationSpeed
zRotationVelocity = Mathf.Clamp(zRotationVelocity, -maxRotationSpeed, maxRotationSpeed);
// update transform
transform.position += velocity * Time.deltaTime;
transform.Rotate(0, 0, zRotationVelocity * Time.deltaTime);
}
}
Your answer
Follow this Question
Related Questions
Advice on my Ship AI... 4 Answers
How to check if one GameObject is in the way of another GameObject? 1 Answer
Manipulating cursor direction in 3D space 0 Answers
Referencing a gameobject in another scene 1 Answer
Move child closer to parent ? 1 Answer