Unity 2D 碰撞卡死 移动卡死
程序开发
2023-09-03 20:07:35
人物卡死的问题有很多, 目前笔者遇到的解决方案有 trigger 勾选, 改变刚体 Collider, 增加不可移动代码三种.
1. 两个碰撞体间 trigger 勾选
一般而言, 刚体 Rigidbody 所在的 Box Collider 2D 的 trigger 不打勾(打不打勾看项目当时的需求和情况有所改变), 与之相撞的 BX2D 的 trigger 打勾

但大部分项目这种肯定是做好的, 那么就有一种可能是人物底部方形和碰撞体方形重合, 于是有了接下来第二点
2. 改变刚体 Collider
我们可以把刚体底部(或者与碰撞体相撞的地方)设为原型碰撞 Circle Collider 2D

如果这样也不行, 就有可能是刚体移动的代码是强制移动, 这时候我们可以给要被碰撞的物体加一个层级, 再在代码中加一个遇到不可移动的代码
3. 增加不可移动代码
新增层级 Unwalkable, 用了下方代码后在 WhatStopMovement 选择 Unwalkable
再把不想穿过的层级变为 Unwalkable, 就可以实现不卡死碰撞

(这里是刚体的配置)

(案例中把 Titl Palette 改为 StopWalkable, 就不会卡死在wall)
下方的代码移动是和项目的 player 移动相关, 我们是平面俯视移动(不是横版跳跃), 可以酌情参考
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class NewBehaviourScript : MonoBehaviour
{[Header("Movement Speed")]public float moveSpeed = 1f;[Header("Player movement points")]public Transform movePoint;[Header("Movement detection layer")]public LayerMask whatStopMovement;[SerializeField]private GameObject item;/// Virtual axis valuesprivate float ver, hor;//Animation componentsprivate Animator ani;private float nu;// Start is called before the first frame updatevoid Awake(){//Removing movePoint from the playermovePoint.parent = null;//Get the animation component of the first child objectani = transform.GetChild(0).GetComponent(); }private void Start(){}// Update is called once per framevoid Update(){hor = Input.GetAxis("Horizontal");ver = Input.GetAxis("Vertical");transform.position = Vector3.MoveTowards(transform.position, movePoint.position, moveSpeed * Time.deltaTime);if (Vector3.Distance(transform.position, movePoint.position) <= .05f){if (Mathf.Abs(Input.GetAxisRaw("Horizontal")) == 1f){if (!Physics2D.OverlapCircle(movePoint.position + new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f), .2f, whatStopMovement)){movePoint.position += new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f);ani.SetTrigger("Move");this.enabled = true;}}else if (Mathf.Abs(Input.GetAxisRaw("Vertical")) == 1f){if (!Physics2D.OverlapCircle(movePoint.position + new Vector3(0f, Input.GetAxisRaw("Vertical"), 0f), .2f, whatStopMovement)){movePoint.position += new Vector3(0f, Input.GetAxisRaw("Vertical"), 0f);ani.SetTrigger("Move");this.enabled = true;}}if (Vector3.Distance(transform.position, movePoint.position) >= 2f){movePoint.position = GameObject.Find("player").transform.position;}}
}
标签:
相关文章
-
无相关信息