Unity3D基础34.1:打砖块小游戏优化

 

前文:https://blog.csdn.net/Jaihk662/article/details/86768910(打砖块小游戏设计)

前面实现了一个非常的简单打砖块小游戏,但可以发现里面有许多不合理的地方(特性

一、优化:当方块掉下去的时候,到达一定高度后销毁它

给方块添加脚本如下即可:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeDes : MonoBehaviour
{
    private Transform myTran;
    void Start()
    {
        myTran = gameObject.GetComponent<Transform>();
    }
    void Update()
    {
        if (myTran.position.y<=-10)
        {
            GameObject.Destroy(gameObject);
        }
    }
}

 

二、优化:当小球射出去8秒后,让它自动销毁

一样给小球添加脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereDes : MonoBehaviour
{
    void Start()
    {
        GameObject.Destroy(gameObject, 8);
    }
    void Update()
    {
    }
}

 

三、修改:无论鼠标指向哪里,小球都能射出

其实代码多此一举了,根本就没有必要检测射线碰撞,所以需要稍微修改下代码

除此之外,还可以通过直接获取射线的方向,来确定射出小球时力的方向

Ray.direction.x/y/z:获取射线的方向

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(new Vector3(ray.direction.x, ray.direction.y, ray.direction.z) * 1360);       //给予“子弹”一个力
        //}
    }
    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);
            }
        }
    }
}

最终修改后结果:

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值