I am creating a 2D side-scroller for my first game and I have quite a bit done; however, one thing has been giving me trouble for around a week now. I want to shoot where the user taps, so I figure I need to raycast to the point where the user taps and shoot a projectile there and then destroy it when it collides with an object? I have searched and cant find anything related to this, I found examples for raycasting from the camera to a touch but not from the actual character. Any ideas?
Well, in this case you need two things (or possibly 3).
First, you need to know what plane your character is moving on. Usually this would be as simple as creating one with:
Plane dudePlane = new Plane(player.position, Camera.main.forward);
Then, to get the touch position, you can use
float point; Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition) dudePlane.Raycast(camRay, out point); Vector3 position = camRay.GetPoint(point);
Then, finally, get the actual ray by using
Ray shotRay = new Ray(player.position, (position - player.position));
Now, you can use this ray however you like- for shooting a projectile, for calculating a hitscan, anything.
First convert the touch position into world coordinates.
Then you can raycast from the players position to the target position in world space.