我正在开发一款“踢球门”类型的游戏,目的是自学 Unity 3d。我有我想要的界面和功能,游戏看起来像这样:
我在 OnUpdate 中使用一些代码来检测鼠标按钮何时首次按下(或触摸阶段开始)以及何时释放(或触摸阶段结束),并计算滑动方向、距离和持续时间。我想将这些信息转化为“启动”足球的初始速度,但数学似乎有点超出我的范围。
我从这样的事情开始:
rigidbody.velocity = new Vector3(
Mathf.Min(15, swipeDelta.x * .13f),
Mathf.Min(20, swipeDelta.y * yRatio),
5 / swipeDuration);
这当然在我最初的分辨率和纵横比下效果很好,但一旦我改变其中任何一个,就会惨遭失败。我希望代码的分辨率和纵横比更加不可知,或者至少是相对的。上面代码中使用的数字完全是任意的,并且根据迭代测试发现,在我的初始分辨率下可以产生理想的结果。
有什么建议么?
这个想法是获取起点和终点之间的距离和持续时间,并将它们用作速度。
我使用 ScreenToWorldPoint 获取从屏幕坐标到世界坐标的鼠标位置,以便计算世界中的距离,而不是屏幕的像素密度或分辨率。
预期的最小/最大值是在进行任何调整之前获得的功率值。为了获得良好的值,您可以对最小值进行慢速/短划操作,对最大值进行快速长划操作。
所需的最小/最大值是可以产生所需结果的任意值。
您可能需要根据游戏的方向来旋转速度。现在,向上滑动会给出正 y 值,向右滑动会给出正 x 值。
Vector3 startPos;
float startTime;
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
//Store initial values
startPos = Input.mousePosition;
startTime = Time.time;
}
if (Input.GetMouseButtonUp(0))
{
//Get end values
Vector3 endPos = Input.mousePosition;
float endTime = Time.time;
//Mouse positions distance from camera. Might be a better idea to use the cameras near plane
startPos.z = 0.1f
endPos.z = 0.1f
//Makes the input pixel density independent
startPos = Camera.main.ScreenToWorldPoint(startPos);
endPos = Camera.main.ScreenToWorldPoint(endPos);
//The duration of the swipe
float duration = endTime - startTime;
//The direction of the swipe
Vector3 dir = endPos - startPos;
//The distance of the swipe
float distance = dir.magnitude;
//Faster or longer swipes give higher power
float power = distance / duration;
//expected values are what power you get when you try
//desired values are what you want
//you might want these as public values so they can be set from the inspector
const float expectedMin = 50;
const float expectedMax = 60;
const float desiredMin = 15;
const float desiredMax = 20;
//Measure expected power here
Debug.Log(power);
//change power from the range 50...60 to 0...1
power -= expectedMin;
power /= expectedMax - expectedMin;
//clamp value to between 0 and 1
power = Mathf.Clamp01(power);
//change power to the range 15...20
power *= desiredMax - desiredMin;
power += desiredMin;
//take the direction from the swipe. length of the vector is the power
Vector3 velocity = (transform.rotation * dir).normalized * power
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)