ブログ

2Dキャラクタのシンプル移動&ジャンプ

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
	public float moveSpeed;
	public float jumpPower;
	public AudioClip jumpSound;
	private Rigidbody2D rb2d;

	void Start()
	{
		rb2d = GetComponent<Rigidbody2D>();
	}

	void Update()
	{
		float moveX = Input.GetAxis("Horizontal");

		Vector2 movement = new Vector2(moveX, 0);
		rb2d.AddForce(movement * moveSpeed);

		if (Input.GetKeyDown(KeyCode.Space))
		{
			rb2d.velocity = Vector2.up * jumpPower;
			AudioSource.PlayClipAtPoint(jumpSound, Camera.main.transform.position);
		}
	}
}

(必要なコンポーネントの追加)