I have two scripts one called Bullet that is in charge of bullet movement. Right now the bullet has a rigidbody, but the bullets only move to the right. I need it to to be aimed at the player’s position.
Code so far for Bullet script: bulletRigid.velocity = new Vector2(transform.position.x, transform.position.y);
The second script is called Attack and is in charge of Instantiating the bullets:
Vector3 position = new Vector3(farRangeNPC.transform.position.x, farRangeNPC.transform.position.y, farRangeNPC.transform.position.z);
var bullets = MonoBehaviour.Instantiate(prefab, position, Quaternion.identity);
Keep in mind this is a top down game so the bullets are not being aimed at just left and right.
Why would you assign a position to a velocity? A position isn’t a direction & speed.
Also, you don’t need to break down a transform into X, Y & Z to assign it as you did for your “position” assignment. Just do “Vector3 position = farRangeNPC.transform.position”.
Given what I see above, I would highly suggest you follow some scripting or physics tutorials on Unity Learn.
The Attack script is not attached to any Game Object so I can’t manipulate the velocity even by acessing the Bullets script because the Attack Script does not inherit from Mono so I can’t use GetComponent from my understanding?
Although I have added this line on the Attack script and no errors have shown on the IDE. var vel = bullets.GetComponent<Rigidbody2D>().velocity;
If something like this is okay then how would I set the velocity towards the player?
Thank you for replying.
Given two Vector2 bulletPos and playerPos representing the current bullet and player positions respectively and a float bulletSpeed representing the speed you want the bullet to move then do something along the lines of:
You need a reference to the Player, which since it’s not attached to a MonoBehavior, you’re going to either want to store it in a variable when you construct the object (supposing there’s only 1 player), or pass it in the parameters of the method call.