3月21日
继续之前,对move系统进行改进,之前一直是用的boxcollider来进行检测,虽然能实现但效果有点迟钝,不流畅
这次尝试用Physics2D.OverlapCircle,圆形区域检测试试
OverlapCircle(Vector2 point, float radius, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth= Mathf.Infinity);
Parameters 参数
point | Centre of the circle. |
radius | Radius of the circle. |
layerMask | Filter to detect Colliders only on certain layers. |
minDepth | Only include objects with a Z coordinate (depth) greater than this value. |
maxDepth | Only include objects with a Z coordinate (depth) less than this value. |
在左右下各设置一个圆形检测区域
重新写一个collision脚本,将所有的碰撞检测都放在这个脚本中
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collsion : MonoBehaviour
{
public LayerMask groundLayer;
public bool onGround;
public bool onWall;
public bool onRightWall;
public bool onLeftWall;
public int wallSide;
public float collisionRadius = 0.25f;
public Vector2 bottomOffset, rightOffset, leftOffset;
private Color debugCollisionColor = Color.white;//这是为圆形区域设置颜色,方便检测
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
onGround = Physics2D.OverlapCircle((Vector2)transform.position + bottomOffset, collisionRadius, groundLayer);
onWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, collisionRadius, groundLayer)
|| Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, collisionRadius, groundLayer);
onRightWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, collisionRadius, groundLayer);
onLeftWall = Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, collisionRadius, groundLayer);
wallSide = onRightWall ? -1 : 1;
}
void OnDrawGizmos()
{//这是在unity中画出检测区域,方便排错
Gizmos.color = Color.white;
var positions = new Vector2[] { bottomOffset, rightOffset, leftOffset };
Gizmos.DrawWireSphere((Vector2)transform.position + bottomOffset, collisionRadius);
Gizmos.DrawWireSphere((Vector2)transform.position + rightOffset, collisionRadius);
Gizmos.DrawWireSphere((Vector2)transform.position + leftOffset, collisionRadius);
}
}
完成后是这个效果:
这样左右和下面都有碰撞检测
这样就需要在move脚本中调用collision:
private Collsion coll;
coll = GetComponent<Collision>();
把之前的碰撞检测都改成新的方法
完美实现滑墙!
进行一个改进,当在某一边墙,按住方向键才会下滑,不然会直接掉下来
再实现爬墙,基本就是当在墙上按下上的时候,给他一个向上的速度
完整的墙面代码(不包括弹墙跳)
if (coll.onWall)
{
if (Input.GetButtonDown("Jump"))
{
if (coll.onLeftWall)
{
}
else if (coll.onRightWall)
{
}
}
else if (Input.GetKey(KeyCode.UpArrow))
{
wallClimb();
}
else
{
rb.gravityScale = 5;
wallSlide();
}
}
else
{
rb.gravityScale = 1;
}
大概就到这里,因为代码水平的缘故,我发现需要将游戏状态整合起来做,才会更加方便,比如设置bool值,onWall,onGround等等等等,下一个项目开始会从这方面加以改进