0
votes

I 'm working on an RTS and want to place a gameobject on the mouseposition. This works, but the object is placed in the wrong location.

The picture below shows a raycast of where my mouse is. But the object (cube, bottom left of the terrain) gets instantiated nowhere near the raycast.

raycast

This is the code i'm using to get the position, what am I doing wrong?

toBuild.build(Camera.main.ScreenToWorldPoint(hit.point));

2
Could you post more of your code please? Why are you using ScreenToWorldPoint? You seem to use a raycast which already gives a result in world space .. - derHugo
If I use the point from the raycast it gets instantiated closer to the mouse position but still not correct. The actual instantiation is done through: Instantiate(this, location, Quaternion.identity) This being the gameobject, and location is the location from the raycast - Robin van Breukelen
Well so ... Can you show your complete code of the raycast etc? - derHugo
Yes of course here it is, it seperated in different classes but here's the callstack: RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(ray.origin, ray.direction * 500, Color.blue); ... Physics.Raycast(ray, out hit, 500); ... toBuild.build(hit.point); ... Transform transform = Instantiate(this, location, Quaternion.identity).GetComponent<Transform>(); That's it - Robin van Breukelen

2 Answers

1
votes

It looks like that you are raycasting in world space but for some reason, you use the cast hit as a screen position. It should already be in a world position so don't use Camera.main.ScreenToWorldPoint().

0
votes

After some more research I found the reason why the position was incorrect. I had placed a box collider around the terrain and the raycast was hitting that apparently. I removed the box collider and it worked fine.