- Home /
Shoot Bullet At Touch Position : 2D
Hello everyone,
I have one object shooting in x-y plane..,x means horizontal and y means vertical direction.. My bullet is capsule game object with rigidbody component.
Now Whenever i touch on the screen , i want my bullet to translate towards that position.
For touch i have written code as below:
for (var i = 0; i < Input.touchCount; ++i) {
ray = Camera.mainCamera.ScreenPointToRay(Input.GetTouch(i).position);
switch(Input.GetTouch(0).phase)
{
case TouchPhase.Stationary:
if (Physics.Raycast(ray,hit))
{
bulletObject = Instantiate(bulletPrefab , bulletShootPoint.transform.position , bulletPrefab.transform.rotation);
// hitPoint = hit.point;
// var pos = Input.GetTouch(i).position;
hitPoint = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
}
case TouchPhase.Began:
break;
case TouchPhase.Moved:
break;
case TouchPhase.Ended:
break;
}
}
Which code should i write to shoot bullet at exact touch position? Please help me to solve this action. Please guide me.
Thanks in advance for helping me and supporting me..
Answer by robertbu · Sep 30, 2013 at 04:30 PM
I have no idea about your aiming mechanic. But I can address the specific of how to instantiate an object at the touch position. With a 2D game, the camera will usually be some fixed distance from the 2D surface. For example the camera may be at -10 and the surface at 0 on the 'z' axis for a distance of 10 units. Whatever your setup, you need the distance from the camera to the playing surface. To convert a touch into a world space position you can use Camera.ScreenToWorldPoint(). The 'z' component is the positive distance in front of the camera. So using your code above and a 10 unit distance, you could may be:
case TouchPhase.Stationary:
var pos = Input.GetTouch(i);
pos.z = 10;
pos = Camera.main.ScreenToWorldPoint(pos);
bulletObject = Instantiate(bulletPrefab, pos, Quaternion.identity);
sir i have edited my question. I want my bullet to translate at exact touch position.
The easiest way to get your bullet to translate towards the hit point is to have the bullet look at the hit point and then in Update() have the bullet translate forward:
Insert at line 13 above:
bulletObject.transform.LookAt(hitPoint);
Then on the script on the bullet:
transform.Translate(Vector3.forward * speed);
Alternately if you are going to be using the physics engine, you can add force to the bullet ins$$anonymous$$d. For physics, add a Rigidbody to the bullet, probably turn off gravity, and then insert the following two lines at line 13 above:
bulletObject.transform.LookAt(hitPoint);
bulletObject.rigidbody.AddForce(bulletObject.transform.forward * 1000);
Your answer
Follow this Question
Related Questions
Projectile move towards mouse cursor 3 Answers
I can't shoot up or down. HELP! 1 Answer
Fire Bullet To Mouse Position Problem 2 Answers
RayCast Problem : 2d 1 Answer