前文:https://blog.****.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);
}
}
}
}