Unity-simple small game to control the ball (3)

Create a food setup prefab

Create a new cube, set its length, width and height to 0.5, and rotate it so that it looks like it is standing on the ground.

Rename it to Pick up, set the material for it, because there are many food to be created, so create a prefab for it, create a new prefabs folder, directly drag the Pick up in the Hierarchy window to the prefabs folder just created, so Just created its prefab for Pick up.

When modifying prefabs, all game objects generated by prefabs will be modified synchronously.

Because the object has been rotated, it cannot be translated on the ground with its own coordinate axis. At this time, click the button above to change from local to global, and after changing to world coordinates, the copied and rotated object can be translated.

 Copy enough food, create a new empty object, and drag all the newly created food to the empty object to realize the classification.

 Code the food rotation

 Click the Pick up prefab, click Add Component, enter pickUp, click new script->add, a new script is generated, and it is classified into the script folder.

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

public class pickUp : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.Rotate(new Vector3(0,1,0));
    }
}

The above code can realize the food rotation effect.

Impact checking

Add a tag named pick up to the pick up prefab.

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

public class player : MonoBehaviour
{
    private Rigidbody rd;
    // Start is called before the first frame update
    void Start()
    {
        rd = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        rd.AddForce(new Vector3(h,0,v)*5);
    }
    void OnCollisionEnter(Collision collision)
    {
        if(collision.collider.tag=="pick up")
        {
            Destroy(collision.collider.gameObject);
        }
    }
}

Get the collider component on the collided game object. If the tag is pick up, then destroy the game object to achieve the effect of the ball eating food, but there will be a small pause after the collision, we will talk about it next time.

Guess you like

Origin blog.csdn.net/qq_64573579/article/details/127600219