๐Ÿ’ป My Work/๐ŸŽฎ Unity

[์œ ๋‹ˆํ‹ฐ] ์บ๋ฆญํ„ฐ ์›€์ง์ด๊ธฐ, ์‰ฌํ”„ํŠธ ๋ˆ„๋ฅผ ์‹œ ๋‹ฌ๋ฆฌ๊ธฐ

Jaeseo Kim 2022. 11. 11. 17:35

์บ๋ฆญํ„ฐ ์›€์ง์ด๊ธฐ


MovingObject.cs

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

public class MovingObject : MonoBehaviour
{
    public float speed;// ์†๋„
    private Vector3 vector; //x,y,z ์ถ•

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {

        // "Horizontal" : ์šฐ ๋ฐฉํ–ฅํ‚ค : 1, ์ขŒ ๋ฐฉํ–ฅํ‚ค : -1 ๋ฆฌํ„ด
        // "Vertical" : ์ƒ ๋ฐฉํ–ฅํ‚ค : 1, ํ•˜ ๋ฐฉํ–ฅํ‚ค : -1 ๋ฆฌํ„ด
        if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
        {
            vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z); //z์ถ•์€ ์•ˆ ๋ฐ”๋€Œ๋‹ˆ๊นŒ ๊ทธ๋Œ€๋กœ
            
            // update ๋งˆ๋‹ค ํ˜„์žฌ ์˜ค๋ธŒ์ ํŠธ์˜ ์œ„์น˜์— ๋”ํ•ด์คŒ์œผ๋กœ์จ ์ด๋™
            transform.position = transform.position + vector * speed;
        }
    }
}

 

์œ„ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์บ๋ฆญํ„ฐ ์˜ค๋ธŒ์ ํŠธ์— ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

  • ์ธ์ŠคํŽ™ํ„ฐ ์ฐฝ์—์„œ speed ๋ฅผ ์ •ํ•ด์ค๋‹ˆ๋‹ค.

 

 

 

 

์‰ฌํ”„ํŠธ ๋ˆ„๋ฅผ ์‹œ ๋‹ฌ๋ฆฌ๊ธฐ


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

public class MovingObject : MonoBehaviour
{
    public float speed;// ์ •ํ•œ ์†๋„
    private Vector3 vector; //x,y,z ์ถ•

    public float runSpeed; // ์ •ํ•œ ๋‹ฌ๋ฆฌ๋Š” ์†๋„
    private float applyRunSpeed; // ๋‹ฌ๋ฆด์ง€ ๋ง์ง€์— ๋”ฐ๋ผ ๋‹ฌ๋ผ์ง€๋Š” ์†๋„


    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {

        // "Horizontal" : ์šฐ ๋ฐฉํ–ฅํ‚ค : 1, ์ขŒ ๋ฐฉํ–ฅํ‚ค : -1 ๋ฆฌํ„ด
        // "Vertical" : ์ƒ ๋ฐฉํ–ฅํ‚ค : 1, ํ•˜ ๋ฐฉํ–ฅํ‚ค : -1 ๋ฆฌํ„ด
        if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
        {
            // ์‰ฌํ”„ํŠธ ๋ˆŒ๋ €์„ ์‹œ
            if (Input.GetKey(KeyCode.LeftShift))
            {
                applyRunSpeed = runSpeed;
            }
            else
            {
                applyRunSpeed = 0;
            }

            vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z); //z์ถ•์€ ์•ˆ ๋ฐ”๋€Œ๋‹ˆ๊นŒ ๊ทธ๋Œ€๋กœ

                        // update ๋งˆ๋‹ค ํ˜„์žฌ ์˜ค๋ธŒ์ ํŠธ์˜ ์œ„์น˜์— ๋”ํ•ด์คŒ์œผ๋กœ์จ ์ด๋™
            transform.position = transform.position + vector * (speed + applyRunSpeed);

          }
    }
}