- Home /
Shooting with a locked camera position
I'm making a FPS on rails. The camera is locked in a single position so the player can't look around, but can move their cursor around the screen. I have a script for moving the crosshair around the screen. I just can't figure out how I could expand this to instantiate objects (shoot) from the crosshair. Any help is greatly appreciated.
private var screenPoint : Vector3;
private var offset : Vector3;
function Update() {
screenPoint = Camera.main.WorldToScreenPoint (gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint (new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
function OnMouseDrag() {
var curScreenPoint : Vector3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
var curPosition : Vector3 = Camera.main.ScreenToWorldPoint (curScreenPoint) + offset;
transform.position = curPosition;
}
Hi,
Can I ask how you got on with this? I'm doing something very similar and I would love to pick your brain if you managed to get it to work.
I tried to P$$anonymous$$ you but couldn't find the option.
Regards,
Answer by robertbu · Feb 19, 2013 at 04:54 PM
Raycasting is the typical way to solve the problem. Note that a ray does not necessarily hit anything, so you have to calculate a default distance along the ray. Assuming you Instantiated() your projectile just in front of your crosshairs, you can do something like (untested):
var v3LookPoint : Vector3;
var ray : Ray = camera.main.ViewportPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit))
v3LookPoint = hit.point;
else
v3LookPoint = ray.GetPoint(distance);
projectile.gameObject.transform.LookAt(v3LookPoint);
projectile.AddRelativeForce(transform.forward * 2000);
Note if you have gravity in the scene, your projectile will hit low since it will drop some on its way to the target. It is complicated to do a real fix for this problem, but you can fudge the hit point a bit fairly easily.
Your answer
Follow this Question
Related Questions
FPS shooting Help! 1 Answer
How do I make my crosshair more accurate? 2 Answers
crosshair scrip not working 1 Answer
Instanciate Object Problem for Shooting 2 Answers
Object reference not set to an instance of an object 1 Answer