Unity-街机控制枪体左右上下旋转

C#代码实现:

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

public lcass GunManager:MonoBehaviour{
    
    //枪体绕x轴上下旋转的范围幅度为60度
    private float minXRotation=0;    
    private float maxXRotation=60;

    //枪体绕y轴左右旋转的范围幅度120度
    private float maxYRotation=0;
    private float maxYRotation=120;

    void Start(){
    
    }

    void Update(){
    
    //获取输入设备(鼠标)(x,y)坐标位置与屏幕比值
    float xPosPrecent =Input.mousePosition.x/Screen.width;
    float yPosPrecent =Input.mousePosition.y/Screen.height;
    
    //使用Mathf.Clamp方法限制枪体旋转角度
    float xAngle=-Mathf.Clamp(yPosPrecent*maxXRotation,minXRotation,maxXRotation)+30;
    float yAngle= Mathf.Clamp(xPosPrecent*maxYRotation,minYRotation,maxYRotation)-60;
    
    //将旋转角度值赋给枪体
    transform.eulerAngles=new Vector3(xAngle,yAngle,0);

    }
}

详解:

Unity中限制轴向移动范围方法Mathf.Clamp

在游戏中,为了限制GameObject的某一轴向的移动不超过一定的范围,可以用Mathf.Clamp来解决

Mathf.Clamp(float value,float min,float max)

在 Mathf.Clamp 中传入三个参数:value,min,max

限制 value的值在min,max之间,如果value大于max,则返回max,如果value小于min,则返回min,否者返回value;

 

Unity 的五种旋转方式之一:eulerAngles(欧拉角) 

欧拉角是针对GameObject的一个旋转角度值。

具体调试参考:

https://blog.csdn.net/zxy13826134783/article/details/79461816

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值