Unity 2D人物移动实现
效果展示: 代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParentnewController00 : MonoBehaviour
{
private Rigidbody2D rg;
private Collider2D coll;
private Animator anim;
public GameObject lift;
public float dis = 0;
public float hight = 3;
public Transform kid_transform;
public Transform box_transform;
public float moveSpeed, jumpForce;
public Transform groundcheck;
public LayerMask ground;
public bool isGround, isJump;
public bool jumpPressed;
int jumpCount;
float h = 0;
bool walk = true;
float speed = 0;
bool ispulling = false;
void Start()
{
rg = GetComponent<Rigidbody2D>();
coll = GetComponent<Collider2D>();
anim = GetComponent<Animator>();
lift.SetActive(false);
speed = moveSpeed;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W) && jumpCount > 0)
{
Debug.Log("按下了跳跃键");
jumpPressed = true;
}
if (Input.GetKeyUp(KeyCode.W) && jumpCount > 0)
{
Debug.Log("松开跳跃键");
jumpPressed = false;
}
if (Input.GetKey(KeyCode.S))
{
anim.SetBool("down", true);
walk = false;
if (kid_transform.position.y - box_transform.position.y > hight)
lift.SetActive(true);
}
else
{
anim.SetBool("down", false);
walk = true;
lift.SetActive(false);
}
}
private void FixedUpdate()
{
isGround = coll.IsTouchingLayers(ground);
groundMovement();
Jump();
switchJump();
}
void groundMovement()
{
if (walk)
{
if (Input.GetButton("A"))
{
h = -1;
anim.SetBool("running", true);
}
else if (Input.GetButton("D"))
{
h = 1;
anim.SetBool("running", true);
}
else
{
h = 0;
anim.SetBool("running", false);
}
}
transform.Translate(Vector3.right * h * moveSpeed * Time.fixedDeltaTime);
if (h != 0)
{
transform.localScale = new Vector3(h, 1, 1);
}
}
void Jump()
{
if (isGround)
{
jumpCount = 1;
isJump = false;
}
if (jumpPressed && isGround)
{
isJump = true;
rg.velocity = new Vector2(rg.velocity.x, jumpForce);
jumpCount--;
jumpPressed = false;
}
else if (jumpPressed && jumpCount > 0 && isJump)
{
rg.velocity = new Vector2(rg.velocity.x, jumpForce);
jumpCount--;
jumpPressed = false;
}
}
void switchJump()
{
if (isGround)
{
anim.SetBool("jump", false);
}
else if (!isGround && rg.velocity.y > 0)
{
anim.SetBool("jump", true);
}
else if (rg.velocity.y < 0 && !isGround)
{
anim.SetBool("jump", true);
}
}
}
|