- Home /
How to draw and move a crosshair/reticle (2D)?
I want to have a crosshair around my Player at a distance R and angle X. All the old posts I see recommend things like OnGUI
and Texture2D
but apparently those things are old and deprecated so apparently I need to use Canvas GameObjects on the UI layer.
My setup: a Player class with a public GameObject crosshair
field, in which I click+dragged a Canvas I created with GameObject -> UI -> Image (just a simple gif) named Crosshair. It exists in my Game scene as well.
Here's the relevant parts of the code:
public GameObject crosshair;
private GameObject reticle;
private void Start () {
reticle = Instantiate(crosshair, body.position, Quaternion.identity);
}
private void Update() {
SetAimDirection();
}
private void SetAimDirection() {
Debug.Log(reticlePosition);
reticle.transform.position = new Vector3(reticlePosition.x, reticlePosition.y, 0);
}
Despite the Debug.Log reporting real values, the crosshair doesn't move. Oh and for some reason I get a second Crosshair object (called Crosshair (clone)) when I run the game. What's the proper way to do this? Should I be using this Canvas/UI layer approach or something else?
Answer by Legend_Bacon · Mar 07, 2018 at 10:52 AM
Hello there,
If you already have a crosshair in your scene, you don't need the line in Start(). It creates a new crosshair (which is why you have a (clone) in your scene), and assigns your variable "reticle" to it. Because of that, the function SetAimDirection() updates the position of that clone, instead of your real crosshair.
Here's a simple Unity tutorial that might help you.
Hope that helps!
Cheers,
~LegendBacon
After playing around some more, I changed my modifying line to: crosshair.GetComponent<RectTransform>().localPosition = new Vector3(reticlePosition.x, reticlePosition.y, 0);
. I set the Crosshair GameObject's Canvas Render$$anonymous$$ode property to 'World Space', and its size and initial position were all messed up which was making me think it wasn't being rendered (while it was, just way off screen). So I fixed that and I finally got it to work.
And for reference, my original .transform.position = new Vector3()
code also works with that sorted.