Hi all,
i’m working on a shot script, the player can shot right, left and to diagonal directions like right up and right down.
All of this i can make, the player shoting to left, right and right up and right down, but when i make a left up shot the projectile go to left down, and when i make a left down shot the projectile go to left up. Here i have the piece of code:
publicvoidSetPower(int weaponPower,float projectileSpeed,int direction)
{
this.direction = direction;
power = weaponPower;
speed = projectileSpeed;
if(rigidbodyComponent ==null)
rigidbodyComponent =GetComponent();
if(direction >0)
rigidbodyComponent.AddRelativeForce(Vector2.right *100);
else
if(direction <0)
rigidbodyComponent.AddRelativeForce(Vector2.left *100);
}
I know the Vector2.left set a vector (-1, 0) to force, and this can be the problem, but when i use rigidbody2d.velocity i can’t do diagonal shots, if i use happens the Vector2.right when i shot to left the projectile goes to right.
I don’t know who i can do to resolve this, if someone can help.
How about your function takes a Vector2 direction, which you multiply by speed as the force to add. You would just need one addforce statement.
public void SetPower(int weaponPower, float projectileSpeed, Vector2 direction) {
this.direction = direction;
power = weaponPower;
speed = projectileSpeed;
if(rigidbodyComponent == null) {
rigidbodyComponent = GetComponent<Rigidbody2D>();
}
rigidbodyComponent.AddRelativeForce(direction * speed);
}
Ok, but have the same issue, because direction is Vector2.right or Vector2.left, and the Vector2.left send an add relative force (-1, 0) sending the left down shot to up and left up shot to down.
but thanks for your Answer friend!
I don’t know, but i will work in other resolution without the rigidbody2D, but if anyone have an idea about how i can do it with rigidbody2D i taking sugestions! 
You can pass in any direction you want into the function.
Diagonals:
left and down = (-1, -1)
left and up = (-1, 1)
right and up = (1, 1)
right and down = (1, -1)
Nope, with these coordinates the projectile don’t preserve the angle of shot to left side like to right side, putting Vector2.right the angle of the shot are preserved and the projectile flyes in this angle, but if i put the (-1,1) or (-1,-1) the it flyes to up or down but not in the right angle, i will work on other solution without the RigidBody 2D
but i thanks for your answer Jeffrey, thank you.
Something else is going on that is affecting your object’s angle. There’s no reason why you shouldn’t be able to add a force in any random direction you want.
Keep in mind “RelativeForce” is based on the local orientation of the object. Maybe you’re expecting world axis?
Do you mean “AddRelativeForce” or just “AddForce”?