I already looked around to see if there was any post about this question. All I found we’re (2D Sprite Angle, Follow In A Line, etc…) questions that was not for my topic. I am wondering how to make a 2D sprite follow my mouse cursor. I think it has something to do with “transform.position”, but I don’t know. I also, use c# for my coding.
Basically you’re going to want to sample the mouse position and then move your object towards it. I think the following should work.
This code should grab the mouse position and store it in a Vector3 called positionToMoveTo. You need to access the camera to convert the camera view point to the point in the world. I’m also setting Z to 0 since we’re using 2D, but you could use whatever you want. You’d probably want to use the same Z as the object that’s following, so it doesn’t change.
Thank you. I typed all the code in and I received error.
using UnityEngine;
using System.Collections;
public class MouseMove : MonoBehaviour {
public Camera myCamera;
public Sprite mySprite;
public float moveSpeed = 2.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 positionMoveTo = myCamera.ScreenToWorldPoint (Input.mousePosition);
positionMoveTo.z = 0;
mySprite.transform.position = Vector3.MoveTowards (mySprite.transform.position, positionMoveTo, moveSpeed * Time.deltaTime);
}
}
Sprite doesn’t have a transform member because it is neither a game object nor a component. It is just a wrapper for a texture. Use just “transform.position” to move the current game object.
Thank you! I had my camera’s projection on “perspective”, which made the sprite not move. Is there anyway to make it move on “perspective”? If not, it’s not big deal anyways.