religion/Assets/Scripts/MyPlayer.cs
Roman c9e34f623c 任务:搭建基本的系统
1.实现走动
(1.识别摇杆方向给予物体X方向的速度
(2.使用赋予速度的方式使其移动
(3.不管摇杆深度,只管摇杆方向
2.实现跳跃
(1.只能跳跃一段
(2.只有着地的时候能够跳跃
(3.使用赋予速度的方法使其跳跃
3.增大了重力系数以增加2D游戏感
2021-11-21 22:32:29 +08:00

96 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(Rigidbody2D))]
public class MyPlayer : MonoBehaviour
{
[Header("玩家平时地面移动的速度")]
public float speed = 10f;
[Header("玩家跳跃力度的大小")]
public float jumpForce = 10f;
private Rigidbody2D m_rigidbody;//自身刚体租价
private int inputDir;//当前输入方向,-1左1右0静止
private bool isLanding;//记录自己当前是否着地
void Start()
{
Init();//初始化一些参数
}
void Update()
{
}
void FixedUpdate()
{
Move();//处理水平移动
}
//初始化函数
private void Init()
{
m_rigidbody = GetComponent<Rigidbody2D>();//找到自己身上的刚体组件
}
//移动函数,处理水平方向移动
private void Move()
{
//直接修改刚体速度
m_rigidbody.velocity = new Vector2(inputDir * speed,//水平方向以输入方向乘以预设速度大小
m_rigidbody.velocity.y);//垂直方向不变
}
//碰撞检测代码
// _____ _ _ _ _
// / ____| | | (_) (_)
// | | ___ | | |_ ___ _ ___ _ __
// | | / _ \| | | / __| |/ _ \| '_ \
// | |___| (_) | | | \__ \ | (_) | | | |
// \_____\___/|_|_|_|___/_|\___/|_| |_|
private void OnCollisionEnter2D(Collision2D collision)//当有物体碰上
{
if(collision.transform.tag == "地面")
isLanding = true;//若碰撞物体标签为地面,标记自身着地
}
private void OnCollisionExit2D(Collision2D collision)//当有碰撞体离开
{
if(collision.transform.tag == "地面")
isLanding = false;//若碰撞物体标签为地面,标记自身未着地
}
// 以下为操作监听事件
// _____ _ _____ _
// |_ _| | | / ____| | |
// | | _ __ _ __ _ _| |_| (___ _ _ ___| |_ ___ _ __ ___
// | | | '_ \| '_ \| | | | __|\___ \| | | / __| __/ _ \ '_ ` _ \
// _| |_| | | | |_) | |_| | |_ ____) | |_| \__ \ || __/ | | | | |
// |_____|_| |_| .__/ \__,_|\__|_____/ \__, |___/\__\___|_| |_| |_|
// | | __/ |
// |_| |___/
public void OnMove(InputAction.CallbackContext context)//OnMove事件
{
//决定输入方向inputDir
if(!context.ReadValue<float>().Equals(0))
inputDir = (context.ReadValue<float>() > 0) ? 1 : -1;
else inputDir = 0;
}
public void OnJump(InputAction.CallbackContext context)//OnJump事件
{
//当按下跳跃键
if(context.performed)
{
if(isLanding)//如果当前着地
//给予自身刚体
m_rigidbody.velocity = new Vector2(m_rigidbody.velocity.x,//水平方向速度不变
jumpForce);//垂直方向给予预设跳跃速度
}
}
}