游戏大概:
游戏运行时,点击鼠标左键,生成绿色小球,并朝红色方块飞来。点击鼠标右键,红色方块跳起。当红色方块与绿色小球相撞时,绿色小球被弹开。
游戏运行效果:
游戏实现细节:
控制方块代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player1 : MonoBehaviour
{
protected float jump_speed = 12.0f;
public bool is_landing = true; //用来判断发现碰撞时是否为与与地面相撞(也可能是与小球相撞)
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (this.is_landing) //使得落地后才能再次弹起,而不能在空中再次弹起。
{
if (Input.GetMouseButtonDown(0))
{
this.is_landing = false;
//this.GetComponent<Rigidbody>().velocity = new Vector3(0.0f, 12.0f, 0.0f);
this.GetComponent<Rigidbody>().velocity = Vector3.up * this.jump_speed;
}
}
}
void OnCollisionEnter(Collision collision) //和其他游戏对象发生碰撞时调用的方法。
{
if (collision.gameObject.tag == "Floor")
{
this.is_landing = true;
}
}
}
控制小球代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
// Use this for initialization
void Start()
{
this.GetComponent<Rigidbody>().velocity = new Vector3(10.0f, 9.0f, 0.0f);
}
// Update is called once per frame
void Update()
{
}
void OnBecameInvisible() //在游戏对象移动到画面之外不再被绘制时调用的方法。
{
Destroy(this.gameObject); //删除跑出画面之外的小球。
}
}
发射台(空游戏对象):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Launcher : MonoBehaviour
{
public GameObject ballPrefab;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Instantiate(this.ballPrefab); //通过预设生成游戏对象实例的方法。
}
}
}
让方块不被弹开:
选择项目视图中的 Ball 预设。打开 Rigidbody 标签,将 Mass 项的值由 1 改为 0.01.
Mass 值用于设定游戏对象的重量。两个游戏对象发生碰撞时,Mass 值较大的物体将保持原速度继续运动,Mass 值较小的物体则容易因为受到冲击而改变移动的方向。
让小球强烈反弹(设置物理材质):
首先创建物理材质,选择创建 Physic Material. “物理材质” 用于设定弹性系数和摩擦系数等与物理运动相关的属性。
在项目视图中选择新创建的 Physic Material 后,在检视面板中选择 Bounciness , 将其值由0 改为 1 。 这个值越大,游戏对象就越容易被 “弹开”。
再把这个 Physic Material 加到小球的预设中就行了。
消除 “漂浮感”(调整重力大小):
unity3D 在处理数字时,并未特别指定按照米或者厘米为单位进行计算。目前方块和小球的尺寸值都是1. 也就是说现在游戏中,方块的边长为1米,小球的直径为1米。因此现在看到的游戏对象下落速度都比较缓慢,为了消除这种感觉,我们可以减小游戏对象尺寸,也可以增加重力值。
增加重力值: 在窗口顶部菜单中依次点击 Edit ----> Project Settings ----> Physics, 检视面板中将切换显示 PhysicsManager. 将 Gravity 项的 “Y” 值稍微提高一些,比如设为 -20(注意负号),就可以增加重力值了。