Unity-SunnyLand练习记录3-角色水平移动和Tilemap碰撞设置

角色水平移动设置

确定键盘按键事件

  1. Edit,ProjectSettings,Input Manager中查看Axes
  2. 查看Horizontal对应的按键

移动代码的编辑

  1. 首先为角色移动控制创建变量获取角色刚体和设置移动速度

    1
    2
    3
    4
    5
    //1.获取角色刚体
    public Rigidbody2D playerRb;

    //2.声明角色移动速度
    public float playerMoveSpeed = 400.0f;
  2. 创建PlayerMovement函数,并在FixedUpdate中调用它,这样保证在不同配置的机器上每秒移动的距离是一样的

    • 在PlayerMovement函数中,先获取键盘按键事件
    • 然后对角色刚体的速度进行赋值
    • 对于刚体的运动,在FixedUpdate中调用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    void FixedUpdate()
    {
    PlayerMovement();
    }

    void PlayerMobement()
    {
    //获取角色的移动方向 -1,0,1
    float movement = Input.GetAxisRaw("Horizontal");
    //对角色进行移动
    playerRb.velocity = new Vector2(movement * playerMoveSpeed * Time.fixedDeltaTime, playerRb.velocity.y);
    //对角色进行转向
    if (movement!=0)
    {
    this.gameObject.transform.localScale = new Vector3(movement, 1, 1);
    }
    }

移动卡顿的解决

角色移动存在卡顿现象,原因是Tilemap的碰撞体是每个瓦片独立的,之间有缝隙或者Unity要独立计算每个瓦片与角色的碰撞

  • 将瓦片地图的碰撞体设置为复合碰撞体,即整个瓦片地图看作一个整体

  • 添加Composite Colloder 2D之后,会自动添加Rigidbody 2D,此时要把type设置为static,否则地图会因重力而掉落
  • 在Tilemap Collider 2D中勾选Used by Composite,即可将此碰撞体交由Composite Collider 2D管理

用户手册中对Composite Collider 2D的描述:

1
The Composite Collider 2D uses the vertices (geometry) from any of these Colliders, and merges them together into new geometry controlled by the Composite Collider 2D itself.
1
Both the Box Collider 2D and Polygon Collider 2D components have a Used By Composite checkbox. Select this checkbox to attach them to the Composite Collider 2D.
1
When you enable Used by Composite, other properties disappear from that component, as they are now controlled by the attached Composite Collider 2D.

附:关于移动手感的问题

  • 角色移动代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    void PlayerMobement()
    {
    //获取角色的移动方向 -1,0,1
    float movement = Input.GetAxisRaw("Horizontal");
    //对角色进行移动
    playerRb.velocity = new Vector2(movement * playerMoveSpeed * Time.fixedDeltaTime, playerRb.velocity.y);
    //对角色进行转向
    if (movement!=0)
    {
    this.gameObject.transform.localScale = new Vector3(movement, 1, 1);
    }
    }

    其中GetAxisRaw会获取精确的-1,0,1;若使用GetAxis则会有平滑处理。

    • 用户手册中的描述:水平范围和垂直范围从 0 变为 +1 或 -1,以 0.05f 的步幅增加/减少。GetAxisRaw立即从 0 变为 1 或 -1,因此没有步幅。

    若对角色移动采用GetAxis,则会出现轻微的惯性现象,更符合常理,这里为了操作精确而不采用。

    对角色移动时不用if判断是否为0,否则会出现漂移现象,影响手感