- Home /
Moving A 2D Object Forward
I'm instantiating a bullet out of a gun and trying to move it forward in the direction/rotation is was instantiated as in a 2D space, but for some reason nothing works, the bullet doesn't move or it's moving in the wrong direction. I have tried using transform.forward
and transform.right
but non of them works. I will be extremely grateful for every help, this is my first time working with Unity and I'm still trying to learn the ropes.
BTW: This is a top down shooter kind of game.
This is how I instantiate the bullet:
Instantiate(prefab, firingPoint.position, firingPoint.rotation);
And this is the bullet class:
public class Bullet : MonoBehaviour
{
private Vector3 firingPoint;
[SerializeField]
float bulletSpeed = 2;
[SerializeField]
private float maxBulletDistance = 20;
// Start is called before the first frame update
void Start() {
firingPoint = transform.position;
}
// Update is called once per frame
void FixedUpdate() {
MoveBullet();
if (Vector3.Distance(firingPoint, transform.position) > maxBulletDistance) {
Destroy(this.gameObject);
}
}
void MoveBullet() {
transform.position += transform.right * bulletSpeed * Time.deltaTime;
}
}
Answer by xxmariofer · May 21, 2019 at 04:12 PM
first, change the fixedupdate to update (wont fix your issue but fixedupdate should only be used for physics.) there are only 2 posibilities you are using the wrong vector(try using transform.right/left/forward) and if it doesnt work it means you have set somewhere the time.timescale to 0, (so time.deltatime is 0 to)
First of all, thank you for the quick replay. I tried using what you said, but transform.left doesn't exist in my code and the other 2 options move the bullet in random directions. Also, I never touched the timescale so I don't believe this to be the issue...
If they are moving but in random directions it is because the object is rotated,if the object is rotated there qre 2 options, the first just change transform.right for Vector3.right (also test Vectoe3.forward since depends of how you set up your world) or a second solution is create an empty object with 0,0,0 posituin and rotation, make the player child of the new object and make only attach that script TO THE PARENT not the child
Your answer
Follow this Question
Related Questions
OnTriggerEnter2D Running twice when destroying game object. 1 Answer
Instantiate after setting values? 0 Answers
Instantiated objects do not work with Hitboxes(2D) 0 Answers
Draw Gizmos for Non-Monobehaviour objects in an Array 0 Answers
Add acceleration and deceleration for top down 2D movement. 2 Answers