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...