预制体
在Assets里create一个Folder,改名为Prefabs就是预制体。
将obstacle拖进去就可以统一调整
在复制出来这些障碍物时候就可以统一规格。将所有的obstacle放在一个文件里边,比较美观。
物体移动躲避障碍物
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sideWaysForce = 500f;
bool leftPressed;//布尔值判断是否
bool rightPressed;
void Start()
{
}
void Update()//每帧都运行,输入部分放置在这里
{
leftPressed = Input.GetKey("a");
rightPressed= Input.GetKey("d");
}
private void FixedUpdate()//物理类型
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);//均衡不同电脑帧率,forwardForce控制前进速度
if (Input.GetKey("d"))
{
rb.AddForce(sideWaysForce * Time.deltaTime, 0, 0);//siderWaysForce控制左右速度,可以在面板上改变。
}
if (Input.GetKey("a"))
{
rb.AddForce(-sideWaysForce * Time.deltaTime, 0, 0);
}
}
private void OnCollisionEnter(Collision collision)
{
//Debug.Log("We hit Something");
//判断条件if
if (collision.gameObject.tag == "Obstacle")
{
//停止
this.enabled = false;//类让他停下,禁止
rb.isKinematic = true;//碰到障碍物时候停止,可代表角色的死亡
Time.timeScale = 0;//时间停止
// rb.Sleep();//不可以,使用这个x轴还在动
}
}
}
在面板上的player的Inspector面可以将前进和左右移动的速度改变或者将其质量减轻。这两种方法否可以达到控制速度的目的
AddForce Velocity ForceMode
Velocity直接改变物体速度,无视各种外力。
addforce直接模仿物理受力,给物体施加一个力,也会收到其他力的作用。
force:添加一个可持续力到物体,使用他的质量。
Acceleration:添加一个可持续加速度到刚体,忽略他的质量
impulse:添加一个瞬间冲击力到刚体,使用它的质量
VelocityChange:添加一个瞬间速度变化给刚体,忽略它的质量。
那我们添加ForceMode不受质量影响
private void FixedUpdate()
{
if (Input.GetKey("a"))
{
rb.AddForce(sideWaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("d"))
{
rb.AddForce(-sideWaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
在面板处改变sidewaysForce可以减小力。 也可以增大阻尼,Drag改变数值就可以。
在player运动时候我们发现它位置会发生便宜,在刚体里将Freeze Rotation的xyz全部勾选就不会发生偏移。
添加雾化效果 Fog
话不多说,看图,在第四步我们可以选择雾的颜色,调整密度Density增加游戏难度。