- Home /
How to instantiate a gameobject towards touch position from camera ?
How do i instantiate gameobject on touch and Shoot it like in the Smash hit game? I don't want it to shoot forward using Addforce(Vector3.forward) Rather i want to shoot it to the mouseposition from camera.
Answer by hexagonius · Jul 31, 2018 at 11:38 AM
First of all, you need to convert the touch position into the world. For this you use ScreenToWorldPoint on the Camera with the Input.position:
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Even though the Vector given by the input is a Vector2, the transfer needs a Vector3. That's because if the camera is in perspective mode, this would be at the origin of the camera only, where all positions would be returned as the position of the camera. you'd need to define z as the distance from the camera you want the ray to start from, preferably the near clip plane distance of the camera. If you then use the camera's forward vector for your addForce after instantiating your object at the point you received from your conversion, it should fly off from where you tabbed and along the view direction. If you instead use the point you generated minus the camera position as your AddForce, it will fly perspectively away.
I'm a beginner, Can you please provide me a code example. Thank you.
there are plenty of code examples out there to learn and begin with. it's probably best to start using what you can do and add to it:
https://unity3d.com/de/learn/tutorials. these are plenty. look them up, study them, search for what may be already there and study it.
providing you with code here just leads to the next question. learning how to find answers is the better skill
Thanks for you advice but this page is no longer available. Can you suggest me some other?
Your answer
Follow this Question
Related Questions
Camera smooth transistion 2 Answers
Keyboard / Mouse control for FPS 0 Answers
Movie Textures. 0 Answers
FPS weapon natural look 0 Answers
Why is my sprinting animation restricting camera from looking up? 0 Answers