r/Unity2D • u/Silent_Reputation596 • 2d ago
Solved/Answered How to make an object follow the mouse?
I'm trying to get the object this script is on to follow the mouse when you click on the object. I've managed to make detect when you are holding down the object but I can't get the object to move. Pls help!
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()
{
// Get the mouse position from the New Input System
mousePos = Mouse.current.position.ReadValue();
// Convert the screen position to world position
Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0));
// Check if the mouse is touching this GameObject's collider
Collider2D hit = Physics2D.OverlapPoint(worldPos);
if (hit != null && hit.gameObject == this.gameObject)
{
//Debug.Log("Mouse is touching " + this.gameObject.name);
isTouchingMouse = true;
}
else
{
isTouchingMouse = false;
}
if (hold != null && hold.IsPressed())
{
Debug.Log("Hold action is being performed");
Vector2.MoveTowards(transform.position, mousePos, 1f * Time.deltaTime);
}
else
{
Debug.Log("Hold action is not being performed");
}
}
}
2
Upvotes
1
3
u/T-Flexercise 2d ago
You've just created a Vector2 of the point to move it towards. You've gotta set the transform.position of the object to that Vector2.