Unity安卓上的控制脚本

摇杆挂图片脚本

using UnityEngine;
using UnityEngine.EventSystems;

public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
    private RectTransform background; // 摇杆背景
    private RectTransform handle; // 摇杆手柄

    private Vector2 inputDirection; // 输入方向

    private void Awake()
    {
        background = GetComponent<RectTransform>();
        handle = transform.GetChild(0).GetComponent<RectTransform>(); // 摇杆手柄是背景的子元素
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 touchPosition = Vector2.zero;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(background, eventData.position, eventData.pressEventCamera, out touchPosition))
        {
            // 获取触摸位置相对于摇杆背景的百分比
            touchPosition.x = (touchPosition.x / background.sizeDelta.x) * 2;
            touchPosition.y = (touchPosition.y / background.sizeDelta.y) * 2;
            touchPosition = (touchPosition.magnitude > 1f) ? touchPosition.normalized : touchPosition;

            // 更新摇杆手柄的位置
            handle.anchoredPosition = new Vector2(touchPosition.x * (background.sizeDelta.x / 2), touchPosition.y * (background.sizeDelta.y / 2));
            // 更新输入方向
            inputDirection = touchPosition;
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        OnDrag(eventData);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        // 重置摇杆位置和输入方向
        handle.anchoredPosition = Vector2.zero;
        inputDirection = Vector2.zero;
    }

    // 返回输入方向
    public Vector2 GetInputDirection()
    {
        return inputDirection;
    }
}

摇杆移动方向脚本

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

public class JoystickMove : MonoBehaviour
{
    Joystick joystick;
    Joystick joystickRot;
    public float speed = 2.0f;
    public float rotSpeed = 90f;

    void Start()
    {
        GameObject canvas = GameObject.FindGameObjectWithTag("UI");
        joystick = canvas.transform.Find("JoyStick").GetComponent<Joystick>();
        joystickRot = canvas.transform.Find("JoyStickRot").GetComponent<Joystick>();
    }
    void Update()
    {
        Vector2 joystickInput = joystick.GetInputDirection();
        Vector2 joystickRotInput = joystickRot.GetInputDirection();
        Move(joystickInput);
        Rotate(joystickRotInput);
    }

    void Move(Vector2 joystickInput)
    {
        transform.Translate(new Vector3(
            0,
            0,
            joystickInput.y * Time.deltaTime * speed));
        transform.Rotate(0, joystickInput.x * Time.deltaTime * rotSpeed, 0);
    }

    void Rotate(Vector2 joystickRotInput)
    {
        //transform.Translate(new Vector3(
        //    joystickRotInput.x * Time.deltaTime * speed,
        //    //joystickRotInput.y * Time.deltaTime * speed,
        //    0,
        //    0));
        transform.Rotate(joystickRotInput.y * Time.deltaTime * (-rotSpeed),
            joystickRotInput.x * Time.deltaTime * rotSpeed,
            0);
    }

}

摄像头移动脚本挂画板

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// 安卓控制器
/// </summary>

public class MCMoveTouch : MonoBehaviour, IDragHandler, IEndDragHandler
{

    Transform MC;
    Transform plane;

    void Start()
    {
        MC = GameObject.Find("MC").transform;
        plane = GameObject.Find("Plane").transform;
    }

    //旋转最大角度
    public int yRotationMinLimit = -20;
    public int yRotationMaxLimit = 80;
    //旋转速度
    public float xRotationSpeed = 60.0f;
    public float yRotationSpeed = 60.0f;
    //旋转角度
    private float xRotation = 0.0f;
    private float yRotation = 0.0f;

    public void OnDrag(PointerEventData evenntData)
    {
        xRotation -= evenntData.delta.x * xRotationSpeed * 0.02f;
        yRotation += evenntData.delta.y * yRotationSpeed * 0.02f;
        //MC.Rotate(new Vector3(-(evenntData.delta.y + MC.rotation.x), evenntData.delta.x + MC.rotation.y, 0));
        yRotation = ClampValue(yRotation, yRotationMinLimit, yRotationMaxLimit);//这个函数在结尾
        //欧拉角转化为四元数                                                                        
        Quaternion rotation = Quaternion.Euler(-yRotation, -xRotation, 0);
        MC.rotation = rotation;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        yRotation = 0;
        xRotation = 0;
        //设置摄像头方向为Plane的方向
        MC.rotation = plane.rotation;
    }

    float ClampValue(float value, float min, float max)//控制旋转的角度
    {
        if (value < -360) value += 360;
        if (value > 360) value -= 360;
        return Mathf.Clamp(value, min, max);
        //限制value的值在min和max之间, 如果value小于min,返回min。 如果value大于max,返回max,否则返回value
    }

}

点击发射子弹脚本

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

public class ButtonClickAttack : MonoBehaviour
{

    private GameObject bullet;
    private Transform firePos;

    public void Attack()
    {
        bullet = Resources.Load<GameObject>("Bullet");
        firePos = GameObject.Find("Plane").transform.GetChild(0);

        GameObject tempBullet = Instantiate(bullet, firePos.position, firePos.rotation);
        tempBullet.AddComponent<BulletConterl>();
        tempBullet.name = "PlayerBullet";
        Destroy(tempBullet, 5f);
    }
}

UI画板切换脚本

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

public class ChangeCanvas : MonoBehaviour 
{
    public GameObject CanvasOn;
    public GameObject CanvasOff;

    public bool isPause = false;
    public bool isRebegin = false;

    public void changeCanvas()
    {
        CanvasOn.SetActive(true);
        CanvasOff.SetActive(false);
        if (isPause)
        {
            Time.timeScale = 0;
        }
        else
        {
            Time.timeScale = 1;
        }

        if (isRebegin)
        {
            SceneManager.LoadScene("SampleScene");
        }
    }

}

鼠标移动摄像机脚本

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

public class MCMove : MonoBehaviour
{
    public enum MouseState
    {
        None,
        MidMouseBtn,
        LeftMouseBtn
    }

    private MouseState mMouseState = MouseState.None;
    private Camera mCamera;

    private void Awake()
    {
        mCamera = this.transform.GetChild(0).GetComponent<Camera>();
        if (mCamera == null)
        {
            Debug.LogError(GetType() + "camera Get Error ……");
        }

        GetDefaultFov();
    }

    private void LateUpdate()
    {
        CameraRotate();
        CameraFOV();
        CameraMove();
    }

    #region Camera Rotation
    //旋转最大角度
    public int yRotationMinLimit = -20;
    public int yRotationMaxLimit = 80;
    //旋转速度
    public float xRotationSpeed = 250.0f;
    public float yRotationSpeed = 120.0f;
    //旋转角度
    private float xRotation = 0.0f;
    private float yRotation = 0.0f;

    /// <summary>
    /// 鼠标移动进行旋转
    /// </summary>
    void CameraRotate()
    {
        if (mMouseState == MouseState.None)
        {

            //Input.GetAxis("MouseX")获取鼠标移动的X轴的距离
            xRotation -= Input.GetAxis("Mouse X") * xRotationSpeed * 0.02f;
            yRotation += Input.GetAxis("Mouse Y") * yRotationSpeed * 0.02f;

            yRotation = ClampValue(yRotation, yRotationMinLimit, yRotationMaxLimit);//这个函数在结尾
            //欧拉角转化为四元数
            Quaternion rotation = Quaternion.Euler(-yRotation, -xRotation + 180, 0);
            transform.rotation = rotation;

        }
    }

    #endregion
    #region Camera fov
    //fov 最大最小角度
    public int fovMinLimit = 25;
    public int fovMaxLimit = 75;
    //fov 变化速度
    public float fovSpeed = 50.0f;
    //fov 角度
    private float fov = 0.0f;

    void GetDefaultFov()
    {
        fov = mCamera.fieldOfView;
    }

    /// <summary>
    /// 滚轮控制相机视角缩放
    /// </summary>
    public void CameraFOV()
    {
        //获取鼠标滚轮的滑动量
        fov += Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * 100 * -fovSpeed;
        // fov 限制修正
        fov = ClampValue(fov, fovMinLimit, fovMaxLimit);
        //改变相机的 fov
        mCamera.fieldOfView = (fov);
    }

    #endregion
    #region Camera Move
    float _mouseX = 0;
    float _mouseY = 0;
    public float moveSpeed = 1;
    /// <summary>
    /// 中键控制拖动
    /// </summary>
    public void CameraMove()
    {
        if (Input.GetMouseButton(2))
        {
            _mouseX = Input.GetAxis("Mouse X");
            _mouseY = Input.GetAxis("Mouse Y");

            //相机位置的偏移量(Vector3类型,实现原理是:向量的加法)
            Vector3 moveDir = (_mouseX * -transform.right + _mouseY * -transform.forward);

            //限制y轴的偏移量
            moveDir.y = 0;
            transform.position += moveDir * 0.5f * moveSpeed;
        }
        else if (Input.GetMouseButtonDown(2))
        {
            mMouseState = MouseState.MidMouseBtn;
            Debug.Log(GetType() + "mMouseState = " + mMouseState.ToString());
        }
        else if (Input.GetMouseButtonUp(2))
        {
            mMouseState = MouseState.None;
            Debug.Log(GetType() + "mMouseState = " + mMouseState.ToString());
        }

    }

    #endregion
    #region tools ClampValue
    //值范围值限定
    float ClampValue(float value, float min, float max)//控制旋转的角度
    {
        if (value < -360) value += 360;
        if (value > 360) value -= 360;
        return Mathf.Clamp(value, min, max);
        //限制value的值在min和max之间, 如果value小于min,返回min。 如果value大于max,返回max,否则返回value
    }
    #endregion
}

end

评论