- Home /
Question by
iliebotez05 · 6 days ago ·
2dmouseposition
Follow the mouse
How can I make an object follow the mouse in a certain area, and after the mouse leaves the area, the object remains at the edge of the area. When the mouse re-enters the area, the object should follow the mouse again. This is the code at the moment:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowMouse : MonoBehaviour
{
private Vector3 mousePosition;
public float moveSpeed = 0.1f;
void Update()
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613061456im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problem with Vector3 Distance and Mouse Input, 1 Answer
Get Camera mouse position not working correctly in 2D space 2 Answers
Tryna get the position of the mouse in world space 1 Answer
How do I detect mouse inputs on sprites that are on a render texture? 2 Answers
2d mouseposition in a 3d world 3 Answers