Unity 2D物體左右移動腳本(鼠標觸摸+鍵盤)


using UnityEngine;
using System.Collections;

public class Paddle : MonoBehaviour
{
    void Update()
    {
        if (GameManager.Instance.currentState == GameState.Playing && GameManager.Instance != null)
        {
            //鼠標或觸摸
            if (Input.GetMouseButton(0))
            {
                //Create a ray from camera to playfield
                Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
                Plane p = new Plane(Vector3.up, transform.position);

                //Shoot the ray to know where the click/tap found place in 3D
                float distance;
                if (p.Raycast(mouseRay, out distance))
                {
                    //Use current position as starting point
                    Vector3 position = transform.position;
                    //The player can only move the paddle in the x axis, so don't use the y and z
                    position.x = mouseRay.GetPoint(distance).x; //GetPoint gives us the position in 3D
                                                                //Apply the new position
                    transform.position = position;
                }
                else
                {
                    //The ray missed
                }
            }

            // 鍵盤
            else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
            {
                //Use current position as starting point
                Vector3 position = transform.position;
                position.x = position.x - Time.deltaTime * 50;
                transform.position = position;


            }
            else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
            {
                //Use current position as starting point
                Vector3 position = transform.position;
                position.x = position.x + Time.deltaTime * 50;
                transform.position = position;
            }
        }
        
        //Make sure the paddle stays inside the level
        float freedom = 19.25F;
        Vector3 limitedPosition = transform.position;
        if (Mathf.Abs(limitedPosition.x) > freedom)
        {
            //Paddle is outside the level so move it back in
            limitedPosition.x = Mathf.Clamp(transform.position.x, -freedom, freedom);
            transform.position = limitedPosition;
        }
    }
}

 補充:

1.Unity實現物體左右循環移動效果

2.Unity 3D 控制物體前后左右均勻移動腳本

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM