unity台桌小游戏

1、创建桌面

新建一个empty命名为table,创建子物体plane和四个cube,调整位置和大小,并赋予材质设置颜色

table

cube1

 

 cube2

cube3

 

cube4

 

2、给主相机添加代码,使相机始终跟随小球

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

public class cama : MonoBehaviour
{
    public GameObject player;
    private Vector3 offset;
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position;
        player = GameObject.Find("Sphere");
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = player.transform.position + offset;
    }
}

3、新建一个text和rawimage,用来计分和显示游戏结束后的画面,把图片添加到Texture上 

 

4、创建一个小球,添加刚体材质(Add Compoenet-->rigidbody),添加代码,相关注释见代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class move : MonoBehaviour
{
    public float speed=10;
    private int count;
    public Text countText;
    public RawImage abc;
    // Start is called before the first frame update
    void Start()
    {
        count = 0;
        for (int i = 0; i < 12; i++)
        {
            float a = Random.Range(-24f, 24f);
            float b = Random.Range(-2f, 24f);
            float c1= Random.Range(0, 1f);
            float c2 = Random.Range(0, 1f);
            float c3= Random.Range(0, 1f);
            GameObject obj1 = GameObject.CreatePrimitive(PrimitiveType.Cube);
            obj1.transform.position = new Vector3(a, 1f, b);
            obj1.transform.Rotate(45, 45, 45);
            obj1.transform.localScale = new Vector3(1.3f, 1.3f, 1.3f);
            obj1.name = "pickup0";
            obj1.tag = "pickup";
            Material mat = obj1.GetComponent<MeshRenderer>().material;
            mat.SetColor("_Color", new Color(c1, c2, c3, 1));//创建十二个cube,设置大小,位置和颜色随机,并设置标签为pickup
        }
            setCountText();
        abc.enabled = false;//设置画布不可见
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float moveh = Input.GetAxis("Horizontal");
        float movev = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveh, 0.0f, movev);
        GetComponent<Rigidbody>().AddForce(movement * speed * Time.deltaTime);//给小球施加力,使小球运动
    }
        void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "pickup")
        {
            Destroy(other.gameObject);//小球碰到标签为pickup的物体则摧毁物体
            count++;
            setCountText();
        }
        if (count == 12)
        {
            abc.enabled = true;//如果分数等于十二,则游戏结束,设置画布可见
        }
    }
    void setCountText()
    {
        countText.text = "计分:" + count + "/12";//设置分数显示格式
    }

}

5、点击保存后返回unity界面,点击小球,把代码赋予小球,并设置初始值,把text拖到count Text的位置,把rawimage拖到Abc的位置,点击play。

猜你喜欢

转载自blog.csdn.net/lxy20011125/article/details/129317250