Question by
lilBernier · Mar 10, 2018 at 11:10 PM ·
spaceplanetstravel
Traveling between spherical planets
I have been trying to figure out a solution to space travel for the past week, and my brain cant take it anymore. I am here to ask you guys to help. So i want to make it so i can travel between planets. Using the scripts below(Unless you have anybetter scripts for what I am trying to accomplish). I want to make it so the gravity body/player and enemy's go to the closest planet that has the tag "Planet" and i have read the manual on Tags, and saw the "ClosestEnemyTag" example but i just could not figure out how to implement it into the script. Whoever helps me with this is a savior, and I thank you so much.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class GravityBody : MonoBehaviour
{
GravityAttractor planet;
Rigidbody rigidbody;
void Awake()
{
planet = GameObject.FindGameObjectWithTag("Planet").GetComponent<GravityAttractor>();
rigidbody = GetComponent<Rigidbody>();
// Disable rigidbody gravity and rotation as this is simulated in GravityAttractor script
rigidbody.useGravity = false;
rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}
void FixedUpdate()
{
// Allow this body to be influenced by planet's gravity
planet.Attract(rigidbody);
}
}
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
public class GravityAttractor : MonoBehaviour {
private GameObject player;
public float gravity = -10f;
private void Update()
{
}
public void Attract(Rigidbody body)
{
Vector3 gravityUp = (body.position - transform.position).normalized;
Vector3 localUp = body.transform.up;
// Apply downwards gravity to body
body.AddForce(gravityUp * gravity);
// Allign bodies up axis with the centre of planet
body.rotation = Quaternion.FromToRotation(localUp,gravityUp) * body.rotation;
}
}
Comment