注目キーワード

【Unity】プレイヤーを左右に動かすスクリプトを公開

スクリプト

タイトルの通り、Unityでプレイヤーを左右に動かすスクリプトを公開します。コピーしてご自由にお使いください。

左右のみに移動可能なスクリプト

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

public class move : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        var x = Input.GetAxisRaw("Horizontal"); 
        var moveDirection = new Vector2(x, 0).normalized;
        Move(moveDirection); 
    }

    private void Move(Vector2 moveDirection)
    {
        var pos = transform.position;
        var moveSpeed = 6; 
        pos += (Vector3)moveDirection * moveSpeed * Time.deltaTime;
        pos.x = Mathf.Clamp(pos.x, -8.4f, 8.4f);
        pos.y = transform.position.y;
        transform.position = pos;
    }
}

上記のスクリプトを入力することで、AキーとDキーによって左右方向の移動が可能です。

左右移動+ジャンプ可能なスクリプト

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

public class move : MonoBehaviour
{
    public float moveSpeed = 6f;
    public float jumpForce = 5f;
    private Rigidbody2D rb;
    private bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent();
    }

    // Update is called once per frame
    void Update()
    {
        var x = Input.GetAxisRaw("Horizontal"); 
        var moveDirection = new Vector2(x, 0).normalized;
        Move(moveDirection); 
        if (isGrounded && Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }

    private void Move(Vector2 moveDirection)
    {
        var pos = transform.position;
        pos += (Vector3)moveDirection * moveSpeed * Time.deltaTime;
        pos.x = Mathf.Clamp(pos.x, -8.4f, 8.4f);
        pos.y = transform.position.y;
        transform.position = pos;
    }

    private void Jump()
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        isGrounded = false;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.contacts[0].normal.y > 0.5f)
        {
            isGrounded = true;
        }
    }
}

このスクリプトを入力することで、左右方向の移動に加えて、スペースキーを押すことでジャンプが可能です。

解説

上記のclassの名前(スクリプト上ではmoveとなっている)は、ご自身のスクリプト名にあわせて変更してください。また、Unityについての詳細な解説は、以下のシリーズ動画で行っております。お時間が宜しければご覧ください。

computer c code
最新情報をチェックしよう!