unity3D实现物体任意角度自旋转
- 作者: 黄瓜-X
- 来源: 51数据库
- 2021-08-24
本文实例为大家分享了unity3d实现物体任意角度自旋转的具体代码,供大家参考,具体内容如下
主要涉及函数:
input.getaxis(“mouse x”) 可取得鼠标横向(x轴)移动增量
input.getaxis(“mouse y”) 可取得鼠标竖向(y轴)移动增量
通过勾股定理获取拖拽长度,长度越长旋转越快。在project setting--input 可以设置。
这里用cube来做例子,因为方体看旋转比较清楚,如图:

代码如下:
using unityengine;
using system.collections;
public class newbehaviourscript : monobehaviour {
private bool ondrag = false; //是否被拖拽//
public float speed = 6f; //旋转速度//
private float tempspeed; //阻尼速度//
private float axisx = 1;
//鼠标沿水平方向移动的增量//
private float axisy = 1; //鼠标沿竖直方向移动的增量//
private float cxy;
void onmousedown()
{
//接受鼠标按下的事件//
axisx = 0f; axisy = 0f;
}
void onmousedrag() //鼠标拖拽时的操作//
{
ondrag = true;
axisx = -input.getaxis("movex");
//获得鼠标增量//
axisy = input.getaxis("movey");
cxy = mathf.sqrt(axisx * axisx + axisy * axisy); //计算鼠标移动的长度//
if (cxy == 0f) { cxy = 1f; }
}
float rigid() //计算阻尼速度//
{
if (ondrag)
{
tempspeed = speed;
}
else
{
if (tempspeed > 0)
{
tempspeed -= speed * 2 * time.deltatime / cxy; //通过除以鼠标移动长度实现拖拽越长速度减缓越慢//
}
else {
tempspeed = 0;
}
}
return tempspeed;
}
void update()
{
// this.transform.rotate(new vector3(axisy, axisx, 0) * rigid(), space.world); //这个是是按照之前方向一直慢速旋转
if (!input.getmousebutton(0))
{
ondrag = false;
this.transform.rotate(new vector3(axisy, axisx, 0)*0.5f, space.world);
}
}
}
最终效果如图:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
