Adding an image between the unit and target

I want to have a crosshair pop up on the target unit when being shot at, but I am having trouble placing it in the correct location. I can make it appear but not between the shooter and the target. I tried using BulletProjectile.cs as a model but can’t seem to get it to work right.

I have it where the image is attached to the UnitWorldUI of the target and is accessed through a public variable.

If you’re using a prefab similar to a health bar, you could spawn it in at the target’s position + Vector3.up (puts it about mid-body) - (target.transform.position - shooter.transform.position).normalized (puts it about a unit in front of the target…)

I assigned a prefab to the crosshair (called scope here) and then tried putting
Instantiate(scope, targetUnit.transform.position + Vector3.up - (targetUnit.transform.position - unit.transform.position).normalized, Quaternion.identity);

into the State.Aiming part of the Update() function of the shoot action, but it ended up spawning about 30 invisible ones facing the wrong way.

I think the wrong way part has something to do with the rotation, but I am not sure why there are so many or how to get it visible.

I definitely wouldn’t do this in Update(), because it’ll keep on spawning every Update(). Maybe when the Action starts.

I would put the LookAtCamera script on the prefab. This should make it face the right way.

I realized instantiating it would have a problem because it is an image and needs to get onto the UnitWorldUI. Instead of doing that, I just added an image to the enemy UnitWorldUI and made it public in Unit.cs and added LookAtCamera.cs. That’s all working fine, but I can’t seem to figure out how to adjust its position so that it moves to the right place between the shooter and the target.

Currently I have it like this:
targetUnit.preciseScope.transform.localPosition -= (targetUnit.transform.localPosition - unit.transform.localPosition).normalized;

but this is a little bit off when behind and very off when in front. When in front it’s better to add instead of subtract, so maybe adding an if statement where if the difference is above zero then switch it to add would help, but that still doesn’t help it from being off-center. I’m not sure the best way to adjust the position so that it is always in the center between the shooter and target. I have tried all kinds of addition, subtraction, normalized, not normalized, and so on.

Check out WorldToScreenPoint. (called by Camera.main.WorldToScreenPoint). It takes a point in 3d space and tells you where that would be on the screen.

So I gave up on this and ended up placing the image above the target unit by putting the image in the target’s UnitWordUI and turning it on or off using SetActive. It works for what I need right now.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms