我是Unity 3D的新手,并且正在关注Udemy教程以学习该平台。 我在课程中开发了一款游戏GoHippoGo,其中河马的图像在屏幕周围移动到触摸点。
虽然当我尝试使用帆布和面板等...以使游戏适合所有屏幕尺寸时,河马停止移动!触摸时它只会从屏幕上掉下来(太慢了),而不是移动到触摸点。
我尝试在互联网上搜索,甚至是团结论坛,但找不到解决方案。 我的错误可能非常明显,但由于我是新手,请合作: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;
}
}
答案 0 :(得分:1)
尝试使用(RectTransform)transform.position
或GetComponent<RectTransform>().position
(或简称为transform.position
,但我想记住我正在处理 RectTransform 而不是标准< strong>转换)而不是Camera.main.WorldToScreenPoint(transform.position)
:因为画布设置为屏幕空间 - 叠加, RectTransform的全局位置组件将以像素坐标返回X,Y,Z值。
如果您的屏幕是800x600并且您的对象居中,GetComponent<RectTransform>().position
将返回(400.0f,300.0f,0.0f)。