这一章将要学习碰撞的使用。
1.什么是物理系统What is the Physics System?
在Unity中,物理系统常见的数据有重力、推力、和摩擦力等等。
2.增加刚体组件,Add a Rigidbody 2D Component
在层次窗口中,选择Ruby 对象。将它拖动到Prefab文件夹中。双击Ruby 预制体,在视图中,添加Rigidbody 2D组件。并将Gravity Scale设为0,否则物体会因为重力而下降。
3.Disable Gravity
4.Ruby预制体禁用重力 Disable Gravity for the Ruby Prefab
视图中,查找Ruby头,点Override,应用所有。在这里指的是刚体。
5.What is a Collider?
通过碰撞Colliders,才能知道哪些是固体的。
6.增加碰撞到游戏对象中Add Colliders to GameObjects
打开Ruby 预制体,添加Box Collider 2D组件。
对MetalBox Prefab也添加同样的组件Box Collider 2D。但运行时,角色抖动并旋转。
7.Fix Ruby’s Rotation
点击Ruby 预制体,视图中,找到Rigidbody 2D组件。点Constraints 扩展这个,选中Freeze Rotation。
TIP: If you made that change to the instance of Ruby in the Scene and not on the Prefab, use the drop-down Overrides menu to apply the changes to your Prefab.
8.什么是角色抖动 Why is Ruby Jittering?
修改代码解决之。
public class RubyController : MonoBehaviour
{
Rigidbody2D rigidbody2d;
float horizontal;
float vertical;
// Start is called before the first frame update
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
}
void FixedUpdate()
{
Vector2 position = rigidbody2d.position;
position.x = position.x + 3.0f * horizontal * Time.deltaTime;
position.y = position.y + 3.0f * vertical * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
这是计算刚体的位置。
rigidbody2d.MovePosition(position); 表示刚体会移动,但如果碰到其他刚体会中止运行。
9.Fix Ruby's Jittering
10.Review your Changes
11.重置冲突体Resize the Colliders
双击MetalBox Prefab预制体,找到Box Collider component组件。点Edit Collider按钮。
同理,对Ruby修改也一样。
12.增加位图的冲突 Add Tilemap Collision
在层次窗口中,增加Tilemap 游戏对象。增加Tilemap Collider 2D组件对象。
在工程窗口中,选择Tile 文件夹。选择所有不含有水的。在冲突中,选择Collider Type为None。
13.优化位图的冲突 Optimize the Tilemap Collider
在层次中,选择位图游戏对象。增加Composite Collider 2D组件。选中Used By Composite。
在Rigidbody 2D中,Rigidbody Body Type类型设为static。
现在再次运行下,看看效果。
14.Check Your Script