以下是我的Player代码,是很常规的实现,对unity比较熟练的人来说应该不难阅读。
[pre lang="ruby"]using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Transform playerTransform;
private Rigidbody2D body;
public float speed= 2f;
private bool onGround;
public float jumpPower = 150;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
onGround = false;
}
// Update is called once per frame
private void FixedUpdate()
{
KeyboardControl();
}
//碰撞对象脱离与主角的碰撞时
private void OnCollisionExit2D(Collision2D collision)
{
onGround = false;
}
//碰撞对象与主角碰撞并保持接触时
private void OnCollisionStay2D(Collision2D collision)
{
int cnum = collision.contactCount;//获得碰撞点数量
for(int i = 0;i<cnum;i++){
ContactPoint2D contact = collision.GetContact(i);
Debug.Log(contact.normal.y);//前两张图左下角显示了法线向量长度的结果
if(contact.normal.y > 0.8f){
if(!onGround){
onGround = true;
}
}
}
}