解决问题的关键是,使角色在与墙体发生碰撞后,不能再往碰撞方向移动,所以有必要记录角色碰撞时的朝向,同时也要记录“碰撞”的状态。
我这里是2D环境,用了Transform.translate()作为角色控制。其他移动方式如AddForce()、Rigidbody.velocity也可以。
贴一下代码,代码间有注释。
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float xspeed = 5.0f;
public float yspeed = 5.0f;
private float xmove;
private float ymove;
private bool coll = false; // 是否发生碰撞,解决碰撞震动问题
private char faceDirection = 'f'; // 正面是f,背面是b,左面是l,右面是r
private char pre_face; // 碰撞时的朝向
private void Update()
{
xmove = Input.GetAxis("Horizontal") * xspeed * Time.deltaTime;
ymove = Input.GetAxis("Vertical") * yspeed * Time.deltaTime;
if (xmove > 0) faceDirection = 'r';
if (xmove < 0) faceDirection = 'l';
if