(改良)ブロックの端からでもジャンプ可能にする
接地判定の改良
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()
{
// ★改良(接地判定)
// BoxCastの活用
RaycastHit2D hit2d = Physics2D.BoxCast(transform.position, new Vector2(1f, 1f), 0f, Vector2.down, 0.1f, floor);
return hit2d.collider != null;
//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()
{
// ★改良(接地判定)
// BoxCastの活用
RaycastHit2D hit2d = Physics2D.BoxCast(transform.position, new Vector2(1f, 1f), 0f, Vector2.down, 0.1f, floor);
return hit2d.collider != null;
//RaycastHit2D hit2d = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, floor); // Layerで場合分け(ポイント)
//return hit2d.collider != null;
}
}
(改良)ブロックの端からでもジャンプ可能にする