- Home /
I Need help with gravity
I'm trying to make a fps game on a planet that goes around the sun, but when I run the script, the planet starts moving around the sun, but I get thrown off the planet.
I do have a script that's supposed to give the player gravity toward the planet, but it's not.
Can anyone help
This is the code I'm using for the gravity
using UnityEngine;
using System.Collections;
public class GravityScript : MonoBehaviour {
public Transform gravitySource;
public float gravScalar = 4.0f;
public Vector3 rotOffset = Vector3.zero;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
var direction = gravitySource.position - transform.position;
rigidbody.AddForce(direction.normalized * gravScalar);
transform.rotation = Quaternion.LookRotation(direction.normalized)
* Quaternion.Euler(rotOffset);
}
}
The script looks like it will do the job. The rotation is a bit unusual. Are you sure you have the right planet assigned to 'gravitySource'? Are you applying any other forces in any other scripts?
Answer by IgorAherne · Aug 13, 2013 at 09:32 PM
Perhaps your character is set to IsKinematic? Than adding the force won't work for him.
try substituting that line with this:
transform.position -= (direction.normalized - transform.position)*gravScalar;
(assuming the code sits on the player object)
Your answer
Follow this Question
Related Questions
Rigidbody gravity between planets 1 Answer
Unity3D PlanetGravity system? C# 1 Answer
Placing objects help needed 1 Answer