- Home /
Sprite Snap and Follow Mouse
Been having problems getting this short script to have an object snap to round number (int). The object I attached it to continues to have a trailing decimal(float). I have a feeling it's because of "ScreenToWorldPoint". I'm using the 2D mode on unity, and my camera is orthographic. I want an effect similar to grid snapping.
Here's the code:
using UnityEngine;
using System.Collections;
public class MoveSnap : MonoBehaviour {
Vector3 mousePos = new Vector2(0,0);
float mousePosX = 0;
float mousePosY = 0;
// Update is called once per frame
void Update () {
mousePosX = Input.mousePosition.x;
mousePosY = Input.mousePosition.y;
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Round(mousePosX),
Mathf.Round(mousePosY),
10.0f));
}
}
Vector2 mPosition = Input.mousePosition;
Vector3 point = Camera.main.ScreenToWorldPoint(new Vector3(mPosition.x,
mPosition.y,
10.0f));
transform.position = new Vector3($$anonymous$$athf.Round(point.x), $$anonymous$$athf.Round(point.y), $$anonymous$$athf.Round(point.z));
So I need to store the ScreenToWorldPoint data before I assign it to my object. Thanks for the help!
@$$anonymous$$ichaelARoberts, no, you don't. I don't assign ScreenToWorldPoint data to your object. Did not noticed?
that's what I'm saying, you assign it so it's not used directly. You use the data from the variable from the "point" to set the new transform.position data so that it can round correctly.
I also noticed my "mousePos" was a Vector3 type not Vector2.
Thanks again.