The ball automatically rotates around

Idea: The moon revolves around the earth, and the earth revolves around the sun

Right click on the Hierarchy to create three 3D spherical objects: Sphere

And with this hierarchical relationship, name them respectively after selecting and F2 shortcut name

At the same time slightly change their position in the Scene view

 

Then right click on Assets at the Project level to create the script folder Scripts

Create two rotation scripts inside and name them Rotate Rotate1

 

Let us first write the moon: revolution, rotation script Rotate

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotate : MonoBehaviour
{
    //月球自转速度
    private float Rotationspeed = 100.0f;
    //月球公转速度
    private float Revolutionspeed = 100.0f;
    public Transform earth;
    void Start()
    {
        
    }
    void Update()
    {
        //先写自传
        transform.Rotate(Vector3.up * Rotationspeed * Time.deltaTime);
        //再写公转
        //transform.RotateAround(Vector3.zero, Vector3.up, Revolutionspeed * Time.deltaTime);
        transform.RotateAround(earth.position, Vector3.up, Revolutionspeed * Time.deltaTime);
   
    }
}

Rewrite the earth: revolution and rotation script Rotate1

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotate1 : MonoBehaviour
{
    //定义地球自转速度
    private float Rotationspeed1 = 10.0f;
    //定义地球公转速度
    private float Revolutionspeed1 = 10.0f;
    public Transform sun1;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
    
        transform.Rotate(Vector3.up * Rotationspeed1 * Time.deltaTime);

        //transform.RotateAround(Vector3.zero, Vector3.up, Revolutionspeed1 * Time.deltaTime);
        transform.RotateAround(sun1.position, Vector3.up, Revolutionspeed1 * Time.deltaTime);
    }
}

Then we drag the Rotate and Rotate1 scripts to Moon and Earth respectively

We have realized the function of the sphere rotating around it!

Homework:

Self-taught Materials What is material and how to use it

Then add materials to the sun and moon to change their colors

Guess you like

Origin blog.csdn.net/Cddmic/article/details/126266778