- Home /
[Solved] How to shoot an object in front of the player?
I've wrote a script for my firstperson game which parents a football in front of the player.
My aim is to shoot the ball in front of the player if i press the left Mousebutton and hold down the "W" Key. Unfortunatelly i don't know how to give the ball a force to shoot it in front of the player. Would be nice if someone could help me to achive this! :)
I made a video about my Problem, maybe it helps to solve it: http://youtu.be/yMmylRfqZ4U
Thanks in advance for any help!
Greetings
-Edd
Here is my Script which i have put to the football:
var thePlayer : CharacterController = GetComponent(CharacterController);
var ParentPart : Transform; //An empty object which is parented in front of the player
var PickUpDistance : float = 2.4;
var canPickUp : boolean = false;
var parented : boolean = false;
function Update ()
{
//is the player near enough to the football to pick it up?
dist = Vector3.Distance(thePlayer.transform.position, transform.position);
if (dist <= PickUpDistance) {canPickUp = true;} else { canPickUp = false; }
//take the ball (parent it to the empty objekt which is parented to the player)
if(Input.GetButtonDown("Fire2") && canPickUp)
{
transform.parent = ParentPart;
parented = true;
}
//Shoot
if(Input.GetButtonDown("Fire1") && Input.GetKey(KeyCode.W) && parented)
{
parented = false;
transform.parent = null;
transform.rigidbody.constraints = RigidbodyConstraints.None;
transform.rigidbody.AddForce (thePlayer.velocity.x,thePlayer.velocity.y,(thePlayer.velocity.z+100));
}
//set the balls position to the position of the empty
if(parented)
{
transform.position = ParentPart.position;
transform.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
}
}
Answer by PlasmaByte · Dec 29, 2013 at 02:44 PM
You can use the forward variable in the transform component to get the current direction the player is facing. You can then add vectors in a much more intuitive way.
transform.rigidbody.AddForce (thePlayer.velocity + thePlayer.transform.forward*100);
This works great, thank you so much :) but you have to use a bigger factor otherwhise you won't notice the effect.
Unfortunatelly i can't upvote your answer, since i need at least a reputation of 15, but i will do as soon as possible. THX!
Your answer
Follow this Question
Related Questions
Adding force to rigidbody2d to slide 1 Answer
How can I move an object a specific distance using AddForce? 2 Answers
AddForce Relative to Rotation 1 Answer
Ball Rotating Help 0 Answers