using System.Collections;
using System.Collections.Generic;
using UnityEditor.Callbacks;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float jumpForce = 7f;
[SerializeField] private AudioSource jumpSoundEffect;
private enum MovementState { idle, running, jumping, falling };
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
/*
if (Input.GetKeyDown("space"))
{
GetComponent<Rigidbody2D>().velocity = new Vector3(0, 7, 0);
}
*/
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGround())
{
jumpSoundEffect.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
UpdateAnimationState();
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
// anim.SetBool("running", true);
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
// anim.SetBool("running", true);
state = MovementState.running;
sprite.flipX = true;
}
else
{
// anim.SetBool("running", false);
state = MovementState.idle;
}
if (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}
anim.SetInteger("state", (int)state);
}
private bool IsGround()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}
untiy2d角色移动脚本
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 本文利用刚体实现玩家的移动,使用刚体移动可以产生与其他刚体碰撞立即停止,防止抖动。 1.给角色创建刚体和碰撞体 选...
- 注意本脚本是用刚体移动一定要给物体叫加上刚体组件,并且人物动作动画使用mecanima的混合树“forward”播放
- 1. 简介 在Unity3D中,有多种方式可以改变物体的坐标,实现移动的目的,其本质是每帧修改物体的positio...
- 文章导读 2D像素主要痛点是,2D平面的角色,在3D场景中移动时旋转的控制,即面片要永远面朝镜头,同时允许...
- 2D / 3D摇杆控制角色移动(原理讲解 + 源码分享)CocosCreator 源码在末尾 前言 一年前我在Co...