- Home /
How to add a gravity vector/force to my playerShip's current velocity?
I'm pretty sure I'm making this way more complicated than it needs to be. I'm trying to add a vector3 to another vector3, just like the question says, but I want to vary the additive vector by a planet's mass. The object being that the gravity of a planet bends the trajectory of a ship. If the ship is close enough and going at the right speed it will go into an orbit. Anyway, here's what I have. I think my trig is wrong. My ship's code is pretty simple, it accelerates along the positive x axis until it reaches it's max speed. I know this is kinda a newb question, but hey, that's what I am. New to both coding and Unity. Cheers y'all.
sing UnityEngine; using System.Collections;
public class GravitateTo : MonoBehaviour {
//public float grav = new Vector3;
public GameObject player;
public float mass;
private Rigidbody playerRB;
private Rigidbody RB;
private float grav;
// Use this for initialization
void Start () {
Rigidbody RB = GetComponent<Rigidbody> ();
Rigidbody playerRB = player.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
float dist = Vector3.Distance (playerRB.position, RB.position); //distance from the planet
float angle = Vector3.Angle(playerRB.position, RB.position); //direction the gravity force will be exerted
if (dist > 0) {
grav = mass / (dist * dist); //gravity magnitude
}
//Figure out the vector for gravity
float xVal = grav * Mathf.Tan (angle);
float zVal = grav * Mathf.Cos (angle);
//playerRB.AddForce (xVal, 0f, zVal, ForceMode.Acceleration);
//playerRB.rotation = Quaternion.Euler (0.0f, angle, 0.0f);
Vector3 gravMag = new Vector3 (xVal, 0, zVal);
Vector3 shipPos = new Vector3 (playerRB.transform.position.x, playerRB.transform.position.y, playerRB.transform.position.z);
shipPos += gravMag;
playerRB.transform.position = shipPos;
//Debug.Log (playerRB.transform.position.x + " " + xVal);
}
}
Answer by Owen-Reynolds · May 11, 2015 at 12:55 PM
That won't quite work, since Angle
always returns a positive number (if the planet is 90 degrees to your left or right, Angle says 90.) Not sure what else might be wrong or right, since there's a standard easier way for any sort of pull or push:
Vector toPlanet=(target.position - player.position).normalized();
...
shipPos+=toPlanet*gravMag*Time.deltaTime;
Using normalized direction vectors is just a standard math trick. Time.deltaTime
is a usual Unity frame-rate fix (accounts for gravity being added 60 times.sec.)
Your answer
Follow this Question
Related Questions
Rotating a character's velocity? 3 Answers
Need very specific help with Quaternions 1 Answer
OncollisonEnter2D does not work on moving object 0 Answers
How to make Vector Position Of Character? 1 Answer
Vector math question 1 Answer