【发布时间】:2021-07-10 17:16:25
【问题描述】:
我是 Unity 的新手,正在尝试创建一款 Android 手机游戏。
首先,我决定创建一个名为“SelectObject”的脚本,该脚本将移动对象,前提是对象具有碰撞器。
我将此脚本添加到“MainCamera”组件中,因为我们需要确定相机光线是否接触到对象。
这里是脚本“SelectObject”:
using UnityEngine;
using System.Collections;
public class SelectObject : MonoBehaviour
{
void Start() {
}
public void Update()
{
if ((Input.touchCount > 0) && (Input.touches[0].phase == TouchPhase.Began)) {
Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position);
RaycastHit hit; //Declaring the variable hit, in order to further determine if the camera's ray touhed the object
if (Physics.Raycast(ray, out hit)) {
if (hit.collider != null) { //If the ray of camera touches the collider
hit.collider.GetComponent<Move>().Movement(); //Calling the "Movement" method from script "Move" to move the object
}
}
}
}
}
Move 类是“圆柱体”对象的一个组件,当您单击它时应该移动它。
这里是“移动”类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
public float speedModifier; //Determine the speed of movement
public Touch touch; //Using this variable, we will determine if there was at least some touch on the screen
void Start() {
speedModifier = 2.01f;
}
public void Update() {
}
public void Movement() { //Creating a "Movement" method to call it in the "SelectObject" script
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved) {
transform.position = new Vector3(transform.position.x + touch.deltaPosition.x * speedModifier, transform.position.y, transform.position.z + touch.deltaPosition.y * speedModifier);
}
}
}
但是当我开始游戏时,圆柱体仍然不动。
我做错了什么?
【问题讨论】:
-
嗯,你的第一个条件是
Input.touches[0].phase == TouchPhase.Began,但在你调用的方法中检查if(touch.phase == TouchPhase.Moved).. 两者永远不会同时是true....
标签: c# visual-studio unity3d