アクションゲームの基礎
毎回過去プロジェクトを開くのが面倒なのでメモ。いろいろなところから引っ張ってきてる&ベストな書き方かわからんので自分用ということで……
ジャンプとか移動とか
Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
Rigidbody2D rb;
bool leftBool;
bool rightBool;
[SerializeField] float playerSpeed;
[SerializeField] float playerFlap;
public const int MAX_JUMP_COUNT = 1; // ジャンプできる回数。
int jumpCount = 0;
bool isJump = false;
void Start () {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
leftBool = Input.GetKey(KeyCode.A);
rightBool = Input.GetKey(KeyCode.D);
if (jumpCount < MAX_JUMP_COUNT && Input.GetKey(KeyCode.Space)) isJump = true;
}
void FixedUpdate() {
if (leftBool) transform.position += new Vector3(-playerSpeed, 0,0);
if (rightBool) transform.position += new Vector3(playerSpeed, 0,0);
if (isJump) {
// 速度をクリアして2回目のジャンプも1回目と同じ挙動にする。
rb.velocity = Vector3.zero;
// ジャンプさせる。
rb.AddForce(Vector3.up * flap);
// audioSource.PlayOneShot(jumpOto);
// ジャンプ回数をカウント。
jumpCount++;
// ジャンプを許可する。
isJump = false;
}
}
void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.tag == "Ground") {
jumpCount = 0;
}
}
}
地面にはGroundのタグを付ける。
(逐次追記していきます)