x


Raycast from player to touch point?

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?

more ▼

asked Feb 29, 2012 at 12:00 AM

Adecker gravatar image

Adecker
1 1 2 5

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Feb 29, 2012 at 12:16 AM

syclamoth gravatar image

syclamoth
18.5k 20 28 121

Yeah, actually 3.

Feb 29, 2012 at 12:17 AM syclamoth

is that C#, boo, or js? I cant tell lol

Feb 29, 2012 at 02:27 AM Adecker

This is pretty obviously C#.

Mar 01, 2012 at 06:38 AM syclamoth

How can i use that ray with a shoot function that uses a rigidBody and addForce?

May 10, 2012 at 02:40 PM oziriz

@syclamoth can you please help me out in the case where i want to move my player to touch position on Android device gradually but not instantly.

Apr 17, 2013 at 01:38 PM rohit_garg
(comments are locked)
10|3000 characters needed characters left

First convert the touch position into world coordinates. Then you can raycast from the players position to the target position in world space.

more ▼

answered Feb 29, 2012 at 12:29 AM

ChrisMasterton gravatar image

ChrisMasterton
16 1

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4988
x2958
x1227
x937
x436

asked: Feb 29, 2012 at 12:00 AM

Seen: 4390 times

Last Updated: Apr 17, 2013 at 01:38 PM