- Home /
Shooting 2D - how to fix
Hi, I was trying to implement shooting in my game, and added some code to a prefab that's a 'shot' and is being cloned every Input.getbutton. But my problem is that when the prefab is shot it shoots in the direction the character is facing but when the character changes the way it's facing the shot comes back from where it is to that direction. How do I fix this?
public class movement : MonoBehaviour {
public float boostSpeed = 0.4f;
private GameObject player;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance(player.transform.position, transform.position);
if(distance >= 0.5f){
// boostSpeed -= 1;
}
if(player.transform.localScale.x == -1){
rigidbody2D.AddForce(transform.right * -0.4f);
}
if(player.transform.localScale.x == 1){
rigidbody2D.AddForce(transform.right * 0.4f );
}
Debug.Log (player.transform.localScale);
}
}
Answer by NoseKills · Feb 10, 2015 at 07:27 AM
In real world when you shoot a bullet, it doesn't have a force added to it constantly when it flies through the air like you do in Update(). A bullet gets one push when it is shot and that's it. So put the addforce only into start.
If that doesn't give you the desired behaviour, save the direction of the shot (player.transform.localScale.x) in Start() and use that in addForce instead of referencing the player transform directly. Player.transform.localscale apparently changes based on you controls and affects bullets in air.
Your answer
Follow this Question
Related Questions
slingshot script - velocity help needed 1 Answer
How do I create a 2d shooting mechanic (Left and Right)? 1 Answer
Changing prefabs to 2D images 0 Answers
2d shooting. 0 Answers
Change script from 3d to 2d Game. 3 Answers