闲余之际,弄了一下小球在一定的范围之内打方块的小游戏,为了测试一下,没有注意物体的外观和物体的起名
一 创建项目
首先先把场景搭建好,给小球搭建好可以移动的范围,
给小球添加上刚体,物体进行碰撞触发的必要条件,约束好小球的三个轴(x,y,z)的旋转 和 物体z轴的移动
最下方的小cube也需要添加上刚体(rigidbody), 避免两个物体碰撞导致方向发生偏转
因为只移动x轴,所以其他的轴 和 旋转都可以约束一下
二 添加代码
- 添加上小球移动的脚本,碰撞之后旋转方向 和 销毁 cube
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RigBodyMove : MonoBehaviour
{
Rigidbody _rag;
// Start is called before the first frame update
void Start()
{
//获取物体上的rigidbody组件
_rag = gameObject.GetComponent<Rigidbody>();
//取消重力
_rag.useGravity = false;
}
// Update is called once per frame
void Update()
{
//小球一直朝着自己的正方向移动
transform.position += transform.forward * 40 * Time.deltaTime;
}
private void OnCollisionEnter(Collision collision)
{
//求法线向量
Vector3 normal = collision.contacts[0].normal;
//求反射角度
Vector3 _dir =
Vector3.Reflect(transform.forward,normal);
//球面向这个方向
transform.forward = _dir;
//当小球接触到随机生成的物体之后,销毁物体
if (collision.gameObject.tag == "Monster")
{
Destroy(collision.gameObject);
}
}
}
- 下边那个小物体移动的脚本 和 在一定 的范围内生成物体的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveChange : MonoBehaviour
{
GameObject _monster;
float time = 0;
// Start is called before the first frame update
void Start()
{
//Resources加载所需要生成的物体
_monster = Resources.Load<GameObject>("Cube (1)");
}
// Update is called once per frame
void Update()
{
float hor = Input.GetAxis("Horizontal");
//移动最下边的小方块 方便接球
transform.Translate(hor,0,0,Space.Self);
//时间管理器
time += Time.deltaTime ;
//当时间>= 2s的时候
if (time >= 2)
{
//在v3类型中规定的范围内随机生成物体,不进行旋转
Instantiate(_monster,new Vector3 (Random.Range(-27,27),Random.Range(24,40),-0.3f),Quaternion.identity);
//时间归零
time = 0;
}
}
}