- Home /
Instantiate projectile with velocity vector of direction character is facing
Yes, I know, there are a million threads with this exact question. I have followed every single one of them and finally came here to ask what the heck is wrong.
I have a 2D topdown game, with a player that rotates to face the mouse position.
When I click, it instantiates an object which I then want to set a velocity, or AddForce such that it moves in the direction the player was facing at the time of instantiation.
I have tried this several ways:
A script attached to the empty gameObject in front of my character that acts as a spawner, which instantiates the projectile retrieves its reference, and then adds the force/sets velocity on its rigidbody2D component.
A script attached to the empty gameObject/spawner, as above, and a separate script attached to the prefab projectile itself which sets the velocity in the Start() method.
Neither are working. The projectile gets instantiated, but does NOT move at all. The only way I can get it to move is by setting the velocity or addforce to a new Vector2 with constant x,y coordinates i.e. (1, 1).
Here is my sample code:
SAMPLE CODE ATTACHED TO THE "SPAWNER", IN FRONT OF MY CHARACTER;
using UnityEngine;
using System.Collections;
public class PlayerToxinController : MonoBehaviour {
public GameObject toxin;
public Transform spawner;
public float speed = 10.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
GameObject clone = Instantiate (toxin, spawner.position, spawner.rotation) as GameObject;
Rigidbody2D toxin_rb = clone.GetComponent<Rigidbody2D> ();
toxin_rb.AddForce (spawner.forward * speed);
}
}
}
Of course these two scripts are not active at the same time, I'm just showing the ways I've been trying and it's not working. Can't get the projectile to move unless I set a static Vector2.
Thanks for any help! Cheers
Answer by nickostan · Feb 01, 2016 at 05:12 PM
use transform.up for 2D games.
"Forward" is based on depth, which a 2D game does not have.
Depending on your sprite layout, you'll want to use up/right/-up/-right ins$$anonymous$$d.
(Note that Vector3 includes up/down/left/right/forward/back, whereas Transform includes only up/right/forward)
Answer by JoshuaMcKenzie · Feb 01, 2016 at 09:36 PM
you might want to increase the speed quite a bit as well, depending on the mass of your projectile, 10 might not even be enough to make it budge. start with 10000 and half or double it based on if its too fast or too slow.
Or, a much more elegant solution:
toxin_rb.AddForce (spawner.up * speed, Force$$anonymous$$ode.VelocityChange);
Force$$anonymous$$ode includes Impulse and VelocityChange variations to immediately modify velocity without regard to frame rate.
Your answer
Follow this Question
Related Questions
C# Projectile Ricochet After Collision2d 1 Answer
How to calculate projectile range 2 Answers
Aiming a shot in Unity 2d? 0 Answers