I need to create script,which will calculate distance between planets,so the
closest planet to the sun might have red color,and the furthest - blue color. Other’s planets might stay with ussual grey color.
I have no idea how can i do it (
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlanetDistanceColor : MonoBehaviour
{
public Transform sunTransform; // The transform of the sun object
public float maxDistance = 100.0f; // Adjust this value as needed
private Renderer planetRenderer;
private void Start()
{
planetRenderer = GetComponent<Renderer>();
if (planetRenderer != null && sunTransform != null)
{
float distanceToSun = Vector3.Distance(transform.position, sunTransform.position);
// Normalize the distance and use it to interpolate between red and blue
float t = Mathf.InverseLerp(0.0f, maxDistance, distanceToSun);
Color color = Color.Lerp(Color.red, Color.blue, t);
planetRenderer.material.color = color;
}
else
{
Debug.LogError("PlanetDistanceColor script is missing required components.");
}
}
}
Here’s how to use this script:
- Attach the script to each of your planet objects in your Unity scene.
- Create an empty GameObject for the sun and position it where you want the sun to be.
- Assign the sun’s Transform to the
sunTransform
field in each planet’s script component. - Adjust the
maxDistance
field to control the maximum distance at which planets will be blue.
This script calculates the distance of each planet to the sun and interpolates the planet’s color between red and blue based on its distance. Planets closer to the sun will be red, while those farther away will be blue. Make sure your planets have a material with a color property to modify their appearance.
Remember to adjust the maxDistance
value to match your scene’s scale and the desired visual effect.
Generated by ChatGPT Upvote is you like it