六、 世界交互-块的移动 World Interactions - Blocking Movement

这一章将要学习碰撞的使用。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

computerclass

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值