游戏场景预设图
玩法:使蓝色的小球触碰到黄色的开关让门降下去,并且不触碰任何东西进入下一关。
介绍:蓝色的小球是玩家,黄色的是开关用来开绿色点前面的门,红色的是障碍物,黑色的是墙。
创建场景以及绑定代码
首先搭建一个场景把地板的Plane命名为Ground并且把Tag设置为Ground。
然后创建一个Sphere命名为Player并且把Tag设置为Player,添加一个Rigidbody。 (墙只用搭建不需要做任何改动)
在Player上创建一个名为playercontroller的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class playercontroller : MonoBehaviour
{
public Rigidbody rb;//获取玩家的Rigidbody组件
public float moveForce;
Vector3 input;
Vector3 startPos;
public int nextStageIndex;//场景转换到的标签号
private void Start()
{
startPos = GetComponent<Transform>().position;
}
// Get input
void Update () {
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
input =new Vector3(h,0,v).normalized;
//移动代码
}
//Apply phy
private void FixedUpdate()
{
rb.AddForce(input * moveForce);
}
//检测碰撞
private void OnCollisionEnter(Collision collision)
{
GetComponent<Transform>().position = startPos;
}
private void OnTriggerEnter(Collider col)
{
if(col .tag =="Goal")
{
SceneManager.LoadScene(nextStageIndex);
//场景转换
}
}
//这个代码是获取移动代码(施加力的移动)、以及触碰到跳关的物体场景装换
}
创建一个cube命名为DoorTrigger并且把Tag设置为DoorTrigger,然后添加一个黄色的材质球,用来当做开门的开关。
创建一个cube命名为Door当做门。
在创建一个cube命名为Goal并且把Tag设置为Goal(这里要注意Goal的高度要比地板高一点点就好)。
在DoorTrigger上创建一个名为DoorTrigger的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorTrigger : MonoBehaviour {
public GameObject door;
bool isActive;
// Update is called once per frame
void Update ()
{
if(isActive&&door.GetComponent<Transform>().position.y>-3f)
//下降的距离
{
door.GetComponent<Transform>().position -= new Vector3(0, 1f * Time.deltaTime, 0);
//下降的速度
}
}
private void OnTriggerEnter(Collider col)
{
if(col.tag=="Player")
{
//检测到玩家触碰后开门
isActive = true;
}
}
//这个代码是当玩家碰到开关的时候让门降下去
}
障碍物
这里是用两个cube组成一个旋转的障碍物
创建一个空物体命名为Rotator,在Rotator中创建两个cube。
在Rotator上创建一个名为Rotator的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotator : MonoBehaviour {
public float rotateSpeed;//定义旋转速度
// Update is called once per frame
void Update ()
{
GetComponent<Transform>().Rotate(Vector3.up, rotateSpeed * Time.deltaTime);
}
}
场景转换
当所有东西都创建好后点击File-Build Settings
把当前的主场景拖进去。我这里是拖拽了一个场景当做下一关。
在Player的脚本上找到nextStageIndex,数字1指的是Level02后面的序号,同理在场景2中设置Player脚本跳转的序号即可。
做好所有的东西后,就做出了一个简单的闯关游戏。