在第二节我们提到后续我们可以给平面上的两个物体添加刚体属性,因为目前物体不具备实际物体的属性,遇到两物体相遇时仍然能够彼此通过,添加刚体属性后的情况实践一下就知道。

现在分别给圆形和方形物理添加刚体属性rigidbody。添加刚体前需要先给两个物体添加一个平面支柱,以免两个图形具有自然物体属性后因重力掉落至空间深处。

添加一个图片名字为background.png,为图片增加Box Collider 2D组件属性,使其能够当做两物体的平面落地支撑。位置稍微下移一些,可用于观察两图形一会具有刚体属性时的自然下落。

unity 物理系统 fixedupdate unity添加物理属性_游戏引擎


给两图形分别添加刚体属性(rigidbody)和碰撞盒属性(collider box),一般情况下刚体和碰撞盒属性是同步添加的,刚体使物体具有实际物理属性,碰撞盒属性使物体具有不可被其他物体穿越的属性。圆形的两个属性,

unity 物理系统 fixedupdate unity添加物理属性_Time_02


方形的两个属性

unity 物理系统 fixedupdate unity添加物理属性_Time_03

圆形的移动属性代码,默认没有初速度的值,即移动起来比较慢。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
  if (Input.GetKey(KeyCode.W))
  {
  	this.gameObject.transform.Translate(Vector3.up*Time.deltaTime);
  	}
   if (Input.GetKey(KeyCode.S))
    {
        this.gameObject.transform.Translate(Vector3.down * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.A))
    {
        this.gameObject.transform.Translate(Vector3.left * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.D))
    {
        this.gameObject.transform.Translate(Vector3.right * Time.deltaTime);
    }

}

}

而方形的移动属性我们设置的稍微快一些,给一个初速度的参数speed=5f;这样一会用于对比方形和圆形的移动速度
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SquareMovement : MonoBehaviour
{
public float speed=5f;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.UpArrow))
  {
  	this.gameObject.transform.Translate(Vector3.up*Time.deltaTime*speed);
  	}
   if (Input.GetKey(KeyCode.DownArrow))
    {
        this.gameObject.transform.Translate(Vector3.down * Time.deltaTime*speed);
    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        this.gameObject.transform.Translate(Vector3.left * Time.deltaTime*speed);
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        this.gameObject.transform.Translate(Vector3.right * Time.deltaTime*speed);
    }
}

}

运行程序,看一下效果。


二维平面移动具有刚体属性的两物体-初速度不同20221016


从效果中能够看到圆形移动的比较慢,而方形由于具备初速度,所以在平面上的移动速度快,并且在相同重力作用下,移动速度快而具备了朝着移动方向更大的推力。在同时按下圆形和方形互斥方向时,即圆形朝右侧移动但方形朝左侧移动,圆形和方形相遇后,方形能够推动圆形朝着左侧移动。