頑張ってゲーム作ることにする #2 キャラクターが動くようにする
今回はキャラクターが動くようにします。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { // Player move speed const float MOVE_SPEED = 3; float moveSpeed; // Rigidbody2d setting private Rigidbody2D rb; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { } void FixedUpdate() { float x = Input.GetAxis("Horizontal"); if (x > 0)// move right { transform.localScale = new Vector2(1, 1); moveSpeed = MOVE_SPEED; Debug.Log("1"); } else if (x < 0) // move left { transform.localScale = new Vector2(-1, 1); moveSpeed = -1 * MOVE_SPEED; Debug.Log("-1"); } else { moveSpeed = 0; Debug.Log("0"); } rb.velocity = new Vector2(moveSpeed, rb.velocity.y); } }
このスクリプトをPlayerにアタッチします。
FixedUpdate内の条件分岐に関してなのですが、xが0から分岐を設定しているとどうやらダメらしかったので、そこだけ注意します。