Unity 鼠标控制/手指控制 物体左右惯性滑动旋转,上下限制角度一些脚本总结

这篇博客总结了Unity中物体惯性旋转的多种方法,包括物体自动旋转、左右惯性滑动并限制角度、支持鼠标和触控屏的操作。特别提到了在触控屏环境下,如何通过Input.touches获取输入,并提供了不同场景下的脚本应用实例,如物体和相机的旋转控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结一些物体惯性旋转方式,项目中用到了第二种,也推荐旋转相机,可以用一个单独的相机照射模型。另外,触控屏获取 Input.GetAxis(“Mouse X”) 获取不到,使用 Input.touches[0].deltaPosition.x 来代替。

物体自动旋转

在这里插入图片描述
脚本放在 Cube 上

using UnityEngine;

//物体添加刚体,忽略重力

// 自动围绕 Y 轴旋转
public class Spin : MonoBehaviour
{
	public Vector3 rotationsPerSecond = new Vector3(0f, 0.1f, 0f);
	public bool ignoreTimeScale = false;

	Rigidbody mRb;
	Transform mTrans;

	void Start ()
	{
		mTrans = transform;
		mRb = GetComponent<Rigidbody>();
	}

	void Update ()
	{
		if (mRb == null)
		{
			ApplyDelta(ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime);
		}
	}

	void FixedUpdate ()
	{
		if (mRb != null)
		{
			ApplyDelta(Time.deltaTime);
		}
	}

	public void ApplyDelta (float delta)
	{
		delta *= Mathf.Rad2Deg * Mathf.PI * 2f;
		Quaternion offset = Quaternion.Euler(rotationsPerSecond * delta);

		if (mRb == null)
		{
			mTrans.rotation = mTrans.rotation * offset;
		}
		else
		{
			mRb.MoveRotation(mRb.rotation * offset);
		}
	}
}

using UnityEngine;


public class RealTime : MonoBehaviour
{
	static RealTime mInst;

	float mRealTime = 0f;
	float mRealDelta = 0f;

	/// <summary>
	/// Real time since startup.
	/// </summary>

	static public float time
	{
		get
		{
#if UNITY_EDITOR
			if (!Application.isPlaying) return Time.realtimeSinceStartup;
#endif
			if (mInst == null) Spawn();
			return mInst.mRealTime;
		}
	}

	/// <summary>
	/// Real delta time.
	/// </summary>

	static public float deltaTime
	{
		get
		{
#if UNITY_EDITOR
			if (!Application.isPlaying) return 0f;
#endif
			if (mInst == null) Spawn();
			return mInst.mRealDelta;
		}
	}

	static void Spawn ()
	{
		GameObject go = new GameObject("_RealTime");
		DontDestroyOnLoad(go);
		mInst = go.AddComponent<RealTime>();
		mInst.mRealTime = Time.realtimeSinceStartup;
	}

	void Update ()
	{
		float rt = Time.realtimeSinceStartup;
		mRealDelta = Mathf.Clamp01(rt - mRealTime);
		mRealTime = rt;
	}
}

左右惯性滑动,上下滑动,同时有角度限制

在这里插入图片描述
脚本放在照射 Cube 的相机上,实际转的是相机,不是模型。通过勾选脚本中的 Is Touch 选择是鼠标操作还是触控屏操作。
下面是触控操作效果:
在这里插入图片描述

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

public class ModelTest : MonoBehaviour
{
    public Transform target;
    public bool _isTouch;
    public float distance = 5.0f;
    public float xSpeed = 120.0f;//
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值