using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
[SerializeField]
private bool staticObject; // Whether this object should be affected by gravity
private float distance; //Distance to the target in the formula eg. r
private bool targetMass; // The mass of the target eg. Mass2
private float gravitationalConstant; // Constant of gravity. Affects how much gravity moves things.
private float force; //Force of gravity
private Vector3 direction; //Direction to apply force
public bool mass; //Mass of object
GameObject[] gravityObjects;
}
// Update is called once per frame
void Update()
{
if(!staticObject)
{
gravityObjects = GameObject.FindGameObjectsWithTag("gravityWell");
foreach(GameObject gravityObject in GravityObjects)
{
//Formula Here!
distance = Vector3.Distance(gravityObject.transform.position, transform.position); //R Variable In Formula
targetGravityScript cs = gravityObject.GetComponent(GravityScript); //Get script component in the target object
float targetMass = cs.mass; //Get the mass variable from that script
// All variables found. Now the calculation
force = gravitationalConstant*((mass*targetMass)/(Mathf.Exp(distance))); //Newton's law of universal gravitation
//Get the direction to apply the force
direction = (target.position - player.position);
direction = direction.normalized;
//Now finally apply that force
rigidbody.AddForce(direction * force);
}
}
}
}
Here is my code. I am trying to make a gravity script for a game but I can’t seem to find the errors that it says are there.
