- Home /
Problem with Instantiating object at Raycast hit point.
Hey everyone, I'm having problems with raycast. I'm trying to instantiate a gameobject at the position where the raycast hits. The raycast always sends from the centre of the screen. Whenever I test this out without maximizing the screen, it works perfectly but when maximized, the object instantiates at only a small distance from the player. I've narrowed it down to the code where I find the centre of the screen, but I'm unsre how this is having an effect on the raycast distance. Here's my code.
if(Input.GetMouseButtonDown(1)){
Ray ray = Camera.main.ScreenPointToRay(new Vector3((Screen.height * 0.5f), (Screen.width * 0.5f), 0);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 5000)){
object = Instantiate(object, hit.point, Quaternion.identity) as GameObject;
}
Thanks for your help!
Try printing hit.transform.name
? $$anonymous$$aybe a change in aspect ratio is moving something in front of you.
Why do you think it's the "center of screen" code? But, you can check by printing ray.start and ray.direction. Compare start to the camera pos in the game world.
Am I just going crazy, but everytime I've seen someone find the centre of the screen, they've divided by 2 not 0.5f?
Well, dividing by 0.5f ... would multiply by 2, ins$$anonymous$$d of dividing ?
Shouldn't you be using Screen.height/2 and Screen.width/2
Just use a ray whose direction is camera.forward.
The ray's origin is the camera.position.
Eli$$anonymous$$ate this unnecessary step altogether.
Your answer
Follow this Question
Related Questions
Make an instantiated object match the slope of the terrain 1 Answer
Raycast Specific Object/Instantiate Explosion 1 Answer
Instantiate gameobject a certain distance away from transform 2 Answers
How do I instantiate a projectile along the path of a raycast? 0 Answers
Instantiate prefab from original position to click mouse point position 0 Answers