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;
}
}
}
}
private void KeyboardControl(){
float sp = speed * Input.GetAxis("Horizontal");
body.velocity = new Vector2(sp,body.velocity.y);
if(onGround){
if(Input.GetAxis("Vertical")> 0.0f)
{body.AddForce(new Vector2(0.0f,jumpPower));}
}
}
}