Home > Blockchain >  When throwing an object, it only goes right
When throwing an object, it only goes right

Time:06-05

I am making a game about throwing a ball. The mouse cursor is the point, to where player should throw it.

The throwing to the right looks ok (Don't mind the force I added to the ball, it is set to low so I won't chase it for a gif purpose): Throwing right

But when i point to the left, it still spawns the ball and the force is added to right:

Throwing left

I am wondering, how to edit my code, so the direction of a thrown ball is correlated with cursor position.

My OnFire method on Player GameObject looks like this:

    void OnFire(InputValue value)
{
    if(!playerHasABall) {return;}
    Instantiate(ball, ballSpawn.position, transform.rotation);
    playerHasABall = false;
}

And the script, that gives the ball a force looks like this (It is put on the ball GameObject):

{
    [SerializeField] float ballForce = 20f;


    void Start() 
    {
        Throw();    
    }

    public void Throw()
    {
        GetComponent<Rigidbody2D>().AddForce(new Vector2(ballForce * Time.deltaTime, 0f), ForceMode2D.Impulse);
    } 
 }

I would greatly appreciate any nudge in a good direction (No Pun intended)

CodePudding user response:

In the above code you did not point the mouse, the new Vector2 axis (ballForce * Time.deltaTime, 0f) always gives you the right direction and the Time.deltaTime factor greatly reduces the throwing power. To solve the problem, reduce the amount of power and also solve the orientation problem with the following code.

[SerializeField] float ballForce = 5f;
public void Throw()
{
    var mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    var direction = (mousePosition - transform.position);
    direction.z = transform.position.z;
    transform.right = direction.normalized;

    GetComponent<Rigidbody2D>().AddForce(transform.right*ballForce, ForceMode2D.Impulse);
} 
  • Related