我是Unity 3D的新手,并且正在关注Udemy教程以学习该平台。
我在课程中开发了一款GoHippoGo游戏,其中,河马的图像在屏幕上移动到触摸点。
虽然当我尝试使用画布和面板等使游戏适合所有屏幕尺寸时,河马却停止了运动!当被触摸时,它只是掉落到屏幕之外(太慢了),而不是移到触摸点。
我尝试在整个Internet上搜索,甚至在统一论坛上搜索,但找不到解决方案。
我的错误可能非常明显,但是由于我是新手,请配合:P
谢谢
这是我的画布的屏幕截图:
这是我的MoveHippo脚本:
using UnityEngine;
using System.Collections;
public class MoveHippo : MonoBehaviour {
private float lastTouchTime, currentTouchTime;
public float velocityVal;
public float torqueVal;
public float thresholdTime;
void Awake() {
velocityVal = 8.0f;
torqueVal = 200.0f;
thresholdTime = 0.3f;
}
void Update () {
#if UNITY_ANDROID
moveHippoAndroid ();
#endif
#if UNITY_EDITOR
moveHippo();
#endif
}
void moveHippo() { //For testing only in your COMPUTER
Vector3 currentPos, touchedPos, distanceVec;
if (Input.GetMouseButtonDown(0)) {
startRotatingHippoAndStopIt();
}
else if (Input.GetMouseButtonUp(0)) {
currentPos = Camera.main.WorldToScreenPoint (transform.position);
touchedPos = Input.mousePosition;
distanceVec = (touchedPos - currentPos).normalized;
stopRotatingHippoAndMoveIt(distanceVec, velocityVal);
}
}
void moveHippoAndroid() {
Vector3 currentPos, touchedPos, distanceVec;
for (int i = 0; i < Input.touches.Length; i++) {
Touch touch = Input.GetTouch(i);
currentPos = Camera.main.WorldToScreenPoint(transform.position);
touchedPos = touch.position;
distanceVec = (touchedPos - currentPos).normalized;
if (Input.GetTouch(0).phase == TouchPhase.Began) {
startRotatingHippoAndStopIt();
} else if (Input.GetTouch(0).phase == TouchPhase.Ended){
currentTouchTime = Time.time;
if (currentTouchTime - lastTouchTime > thresholdTime) { //No Double Touch detected ...
lastTouchTime = Time.time;
stopRotatingHippoAndMoveIt(distanceVec, velocityVal);
} else if (currentTouchTime - lastTouchTime < thresholdTime){ //Double Touch detected!
lastTouchTime = Time.time;
stopRotatingHippoAndMoveIt(distanceVec, velocityVal*2.0f);
}
}
}
}
void startRotatingHippoAndStopIt() {
// We rorate the hippo...
GetComponent<Rigidbody2D>().fixedAngle = false;
GetComponent<Rigidbody2D>().AddTorque(torqueVal);
// ... and stop it
GetComponent<Rigidbody2D>().velocity=Vector2.zero;
}
void stopRotatingHippoAndMoveIt(Vector3 distanceVec, float velocity) {
// We stop rotating the hippo...
Quaternion hippoQuatern = new Quaternion();
hippoQuatern.eulerAngles = new Vector3(0,0,0);
GetComponent<Rigidbody2D>().fixedAngle = true;
GetComponent<Rigidbody2D>().transform.rotation = hippoQuatern;
// ... and move it.
GetComponent<Rigidbody2D>().velocity = distanceVec*velocity;
}
}
最佳答案
尝试使用(RectTransform)transform.position
或GetComponent<RectTransform>().position
(或简单地使用transform.position
,但我想记住我正在处理RectTransform而不是标准Transform)而不是Camera.main.WorldToScreenPoint(transform.position)
:因为您的Canvas设置为Screen Space-Overlay, RectTransform组件的全局位置将返回像素坐标中的X,Y,Z值。
如果屏幕为800x600,并且对象居中,则GetComponent<RectTransform>().position
将返回(400.0f,300.0f,0.0f)。