Here’s my first level. I want the player to feel like a skilled space rocket pilot, so I created my own gravity system (which you can copy paste, I put it below the image), that’s why the level looks simple, it’s kinda hard to land on the green pad when that big orange is pulling you towards it.
I also liked the shadows in the background, it gives a weird feel to the level, like you are in space but not at all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GG.Core
{
[RequireComponent(typeof(Rigidbody))]
public class Gravity : MonoBehaviour
{
[SerializeField] float gravityStrength = 0;
Rigidbody rgb;
Transform planet;
private void Awake() { rgb = GetComponent<Rigidbody>(); }
private void FixedUpdate() { ApplyGravity(); }
private void ApplyGravity()
{
if (planet != null) { rgb.AddForce(CalculateGravity()); }
}
private Vector3 CalculateGravity()
{
Vector3 gravityDirection = (planet.position - transform.position).normalized;
float gravityFullStrength = gravityStrength * (planet.localScale.x / Vector3.Distance(transform.position, planet.position));
return gravityDirection * gravityFullStrength;
}
private void OnTriggerEnter(Collider other) //Sets the planet
{
if (other.CompareTag("Planet")) { planet = other.transform; }
}
private void OnTriggerExit(Collider other) //Removes the planet
{
if (other.CompareTag("Planet") && other.transform == planet) { planet = null; }
}
}
}
To implement this, you require to do the following things;
- Create a “Planet” tag.
- Add the script to the objects you want to be affected by gravity.
- Objects with the script attached should have disabled the “Use gravity” option in their Rigidbodies.
- The objects that will have gravity (that will pull objects), need a second collider set as trigger, it can be anything, a sphere, a box, a capsule, even an empty game object can work, you can create black holes if you want to. Also set their tag as “Planet”.
Just a little explanation onto what is going on in the “CalculateGravity” method.
- Calculates the direction and normalizes it so we don’t get any weird behavior.
- Then it calculates the gravity’s full strength based on the planet size and distance between the center of the planet and the Player. The bigger the planet and the closer to the ground the harder it will pull.
- Then the values are multiplied to get the directional force we need.
If you want to implement it, go ahead, have fun with it!