Unity3D基础34:打砖块小游戏设计

 

前文:https://blog.csdn.net/Jaihk662/article/details/86768480(物理射线)

这里实现一个简单的“打砖块”小游戏,效果如下:

一、地面和墙壁

第一步:先创建一个"plane"平面和一个"Cube"方块如下,其中Cube添加物理组件,并存储预制体

材质球什么的就不用说了,随便弄一个

第二步:创建脚本,批量生成方块

脚本如下:将其挂在摄像头上,并设置GameObject

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeCreate : MonoBehaviour
{
    private int x, y;
    public GameObject myCube;
    void Start ()
    {
        CreateCube();
    }
    void Update ()
    {
		
    }
    void CreateCube()
    {
        x = 10;
        y = 5;
        for (int i = 0; i <= x; i++)
        {
            for (int j = 0; j <= y; j++)
            {
                GameObject.Instantiate(myCube, new Vector3(i - 5, j + 0.5f, 0), Quaternion.identity);
            }
        }
    }
}

效果如下(运行后):

 

二、射出“子弹”

先实例化一个子弹,仍然要添加物理组件

之后修改原先脚本如下(代码中有注释):搞定

RaycastHit.point:获取射线的碰撞点

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeCreate : MonoBehaviour
{
    private int x, y;
    public GameObject myCube, mySph;
    RaycastHit hit;
    private Ray ray;
    private Transform myTran;
    void Start ()
    {
        CreateCube();
        myTran = gameObject.GetComponent<Transform>();
    }
    void Update ()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Shot();
        }
    }
    void Shot()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))         //使用物理类检测射线的碰撞,如果能射中方块
        {
            GameObject go = GameObject.Instantiate(mySph, myTran.position, Quaternion.identity) as GameObject;      //生成“子弹”
            Vector3 dir = hit.point - myTran.position;      //向量减法:鼠标所在位置 - 当前射出位置
            go.GetComponent<Rigidbody>().AddForce(dir * 160);       //给予“子弹”一个力
        }
    }
    void CreateCube()
    {
        x = 10;
        y = 5;
        for (int i = 0; i <= x; i++)
        {
            for (int j = 0; j <= y; j++)
            {
                GameObject.Instantiate(myCube, new Vector3(i - 5, j + 0.5f, 0), Quaternion.identity);
            }
        }
    }
}

 

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值