- Home /
Can I emulate simple space-like gravity?
Hey! I have this script here, for a 2D side scrolling game. It is attached to my player object.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
//Variables
public float PlayerSpeed = 5f;
public float PlayerRotation = 10f;
public float JumpForce = 800f;
public bool IsRight = false;
public bool CanFlip = true;
//Update Function
void Update () {
//Move
float Move = Input.GetAxis ("Horizontal");
float MoveVertical = Input.GetAxis ("Vertical");
rigidbody2D.velocity = new Vector2 (MoveVertical * PlayerSpeed, rigidbody2D.velocity.x);
rigidbody2D.velocity = new Vector2 (Move * PlayerSpeed, rigidbody2D.velocity.x);
rigidbody2D.AddTorque (Move * PlayerRotation);
rigidbody2D.AddTorque (MoveVertical * PlayerRotation);
//Flip
if (Move > 0 && !IsRight) {
Flip ();
} else if (Move < 0 && IsRight) {
Flip ();
}
//Jump
// if (Input.GetKeyDown (KeyCode.W)) {
// rigidbody2D.AddForce(new Vector2 (0, JumpForce));
// }
}
//Flip Function
void Flip() {
if (CanFlip) {
IsRight = !IsRight;
Vector3 Scale = transform.localScale;
Scale.x *= -1;
transform.localScale = Scale;
}
}
}
It works perfectly! I am able to move my character in all four directions, and a slight torque is applied. What I want to achieve is a way to make the gravity feel a little more floaty, like space. Even when he is not moving I would love to see a slight 'bobbing' around. Is there a fairly simple way to do this?
I am trying the same thing. A bit of slow movement when not moving, but when you use the thrusters (It's a spaceship game) you will still float a little in the direction you went, even after done with thrusters.
Answer by Jeff-Kesselman · May 04, 2014 at 12:41 AM
Well, you wouldn't bob in space. In space, you only move when a force is applied and keep moving in the same way until another force is applied.
You bob on the water because the water under you moves up and down. If you were neutrally bouyent in the air, then you might bob a bit according to wind currents.
So, with that out of the way, what you could do is give yourself a slight drag and then apply a random slight nudge force periodically.
If you are looking for ballon bob where you torque a bit but always return to "up and down", then you would set some light gravity and push a force against it to counterbalance. You would attach an additional child component to the bottom with some additional mass to make the balance off center.
Thanks! Yeah, I wasn't going for a too realistic gravity. When the character is still, it just looks a little lifeless. Thanks for the input!
Answer by johkar · May 04, 2014 at 01:10 AM
http://gamemechanicexplorer.com/#thrust-2
This is not Unity but the math behind it could eventually help you in this case.
Your answer
Follow this Question
Related Questions
Need help with this script 0 Answers
Keep up with falling object - Touches 0 Answers
how to jump at fixed height but faster 0 Answers