【问题标题】:How do I call the "Movement" method of an object in another script? Unity如何在另一个脚本中调用对象的“移动”方法?统一
【发布时间】: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


【解决方案1】:

不是 100% 清楚您要做什么,但您是否尝试过将您的位置传递给 Movement() 方法?像这样。

public void Movement(Vector3 targetLocation) {
    transform.position = targetLocation;
}

那么你会这样称呼它。

Movement(Input.touches[0].position);

我注意到了你的速度修改器,所以请注意。您的代码当前设置的方式将立即将对象移动到触摸位置。如果您想让它以指定的速度平稳地移动到它,您需要查找 Lerping 或存储之前的位置、当前位置和目标位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2014-08-17
    • 2012-10-04
    相关资源
    最近更新 更多