我会试着帮助你。
这里是翻译后的内容:
我试图让这个脚本所在的对象在你点击这个对象时跟随鼠标。 我已经成功地实现了检测你是否在按住这个对象的功能,但我却无法让对象移动。 请帮忙!
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class Food_MB : MonoBehaviour
{
// 是否鼠标正在触摸这个对象
public bool isTouchingMouse = false;
// 是否正在按住
public bool isheld = false;
// 玩家输入
private PlayerInput playerInput;
// 按住动作
private InputAction hold;
// 鼠标位置
private Vector2 mousePos;
void Start()
{
playerInput = GetComponent<PlayerInput>();
if (playerInput != null)
{
hold = playerInput.currentActionMap.FindAction("Hold");
}
}
private void Update()
{
// 获取鼠标位置
mousePos = Mouse.current.position.ReadValue();
// 将屏幕位置转换为世界位置
Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0));
// 检查鼠标是否触摸这个对象的碰撞器
Collider2D hit = Physics2D.OverlapPoint(worldPos);
if (hit != null && hit.gameObject == this.gameObject)
{
// Debug.Log("鼠标正在触摸 " + this.gameObject.name);
isTouchingMouse = true;
}
else
{
isTouchingMouse = false;
}
if (hold != null && hold.IsPressed())
{
Debug.Log("按住动作正在被执行");
Vector2.MoveTowards(transform.position, mousePos, 1f * Time.deltaTime);
}
else
{
Debug.Log("按住动作没有被执行");
}
}
}
如果你需要进一步的帮助,请告诉我。
评论 (0)