Playerの作成6(二段ジャンプの禁止)
二段ジャンプの禁止
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Animator animator;
private SpriteRenderer spriteRenderer;
public float jumpSpeed;
public AudioClip jumpSound;
private Rigidbody2D rb2d;
private AudioSource audioSource;
// ★追加(二段ジャンプ禁止)
public LayerMask floor;
void Start()
{
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
rb2d = GetComponent<Rigidbody2D>();
audioSource = GetComponent<AudioSource>();
}
void Update()
{
float moveH = Input.GetAxisRaw("Horizontal");
Vector2 movement = new Vector2(moveH, 0);
transform.Translate(movement * Time.deltaTime * speed);
animator.SetFloat("Speed", moveH);
if (moveH > 0.5f)
{
spriteRenderer.flipX = false;
}
else if (moveH < -0.5f)
{
spriteRenderer.flipX = true;
}
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded()) // ★追加(二段ジャンプ禁止)
{
rb2d.velocity = Vector2.up * jumpSpeed;
audioSource.PlayOneShot(jumpSound);
animator.SetTrigger("Jump");
}
}
// ★追加(二段ジャンプ禁止)
private bool IsGrounded()
{
RaycastHit2D hit2d = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, floor); // Layerで場合分け(ポイント)
return hit2d.collider != null;
}
}
【2022版】ActionGame2D(全33回)
他のコースを見る二段ジャンプの禁止
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Animator animator;
private SpriteRenderer spriteRenderer;
public float jumpSpeed;
public AudioClip jumpSound;
private Rigidbody2D rb2d;
private AudioSource audioSource;
// ★追加(二段ジャンプ禁止)
public LayerMask floor;
void Start()
{
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
rb2d = GetComponent<Rigidbody2D>();
audioSource = GetComponent<AudioSource>();
}
void Update()
{
float moveH = Input.GetAxisRaw("Horizontal");
Vector2 movement = new Vector2(moveH, 0);
transform.Translate(movement * Time.deltaTime * speed);
animator.SetFloat("Speed", moveH);
if (moveH > 0.5f)
{
spriteRenderer.flipX = false;
}
else if (moveH < -0.5f)
{
spriteRenderer.flipX = true;
}
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded()) // ★追加(二段ジャンプ禁止)
{
rb2d.velocity = Vector2.up * jumpSpeed;
audioSource.PlayOneShot(jumpSound);
animator.SetTrigger("Jump");
}
}
// ★追加(二段ジャンプ禁止)
private bool IsGrounded()
{
RaycastHit2D hit2d = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, floor); // Layerで場合分け(ポイント)
return hit2d.collider != null;
}
}
Playerの作成6(二段ジャンプの禁止)