I’m working on a top-down 2d Zelda-like game and I have a projectile that needs to go in the forward direction( or I guess y, locally to the object) when I tell it to using rigid body2d physics.
Does anyone have a good method for moving objects in the forward direction in unity 2d? I don’t even really need it to be a rigid body method, that just seemed easiest
//assign direction to a vector 2 to avoid confusing the computer, I guess
Vector2 dir = new Vector2(transform.right.x, transform.right.y);
//update position with this number and your speed variable
rb.position += dir * speed;
Why is what an issue? You haven’t described how it’s behaving, or how you expect it to behave.
I have some questions from looking at that code, maybe one of them will help somewhere?
If your ‘dir’ is just the X and Y components of transform.right, why aren’t you just using transform.right? (Do you need to truncate it? If you do, I’ve a gut feel that you can just do Vector2 dir = transform.right; and it’ll truncate the vector for you, but I don’t use Vector2 enough to be sure of that.)
Maybe this is your issue: is dir a unit vector? If it’s not then dir * speed will not give you a vector with the magnitude of speed. I would expect that to be normalised.
You’re multiplying by speed, so why are you not multiplying by Time.deltaTime or similar?
Do you realise that referencing transform.right twice is getting Unity to repeat a bunch of calculations twice? Personally I’d go Vector3 transformRight = transform.right; and then use that variable.
You’re absolutely right, I forgot a whole lot of details. my apologies, my brain is fried right now.
the object in question is instantiated from a different script and is placed in a rotation facing its target. I’m trying to get it to travel in a straight line in the direction it is instantiated in.
currently, the current iteration of code works great as long as the target object is to the right of the object I’m moving, otherwise it shoots off in exactly the opposite direction, and I’m not good enough at math to figure that out right now.
in the case of assigning specifically to a new variable, that was an issue that had cropped up in a previous attempt at making this work and is entirely redundant in this situation, thanks for pointing that out.
That makes sense in principle, and I’m glad you’ve a working solution! However, some details are missing, so this won’t make sense if someone else finds it looking to solve a similar problem.
You calculate ‘dir’ by normalising a value ‘enemyToPlayer’. That seems solid, but where does ‘enemyToPlayer’ come from? And what is ‘projectileToTarget’ used for?