- Home /
How do I get a ball to shoot in the direction that my player is facing
In my game a robot has to shoot a ball into a goal. My problem is that when I shoot it always shoots in the same exact direction. It wont shoot in the direction that the player is facing I am using C#.
using UnityEngine; using System.Collections;
class shooting : MonoBehaviour { public float forward = 100f; public float up = 70f;
//Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionStay(Collision collision) {
if (collision.gameObject.name == ("blue robot")){
if (Input.GetKey (KeyCode.Space))
rigidbody.AddForce (Vector3.right * forward * Time.deltaTime);
if (Input.GetKey (KeyCode.Space))
rigidbody.AddForce (Vector3.up * up * Time.deltaTime);
}
}
}
Answer by cdrandin · Sep 06, 2014 at 10:28 PM
It depends how you are moving your object.
If your robot is facing in the direction of the blue arrow, the forward vector, then to shot forward you need to multiply the force with the direction(i.e Vector3.Forward)
Answer by AlucardJay · Sep 06, 2014 at 10:28 PM
Use the transforms forward/up/right, not the world-space Vector3 forward/up/right, eg :
rigidbody.AddForce (transform.right * forward * Time.deltaTime);
http://docs.unity3d.com/ScriptReference/Transform.html
http://docs.unity3d.com/ScriptReference/Transform-forward.html
http://docs.unity3d.com/ScriptReference/Transform-right.html
I figured out the answer. I used the rigidbody.AddForce (transform.right * forward) and combined it with on collision stay. I then locked the X and Z axis and rotated the ball with my player.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
only detect numerical keyboard input 2 Answers
Using Vector3.distance without the y axis 5 Answers
Is there a similar Command to lineRenderer.SetVertexCount for mesh?? 1 Answer