1
\$\begingroup\$
 public class Ball : MonoBehaviour
{
    public float speedBall = 200f;
    Rigidbody2D rbBall;

    private void Awake()
    {
        rbBall = GetComponent<Rigidbody2D>();
    }
    private void Start()
    {
        addStartingForce();
    }
    private void Update()
    {
        
    }

    void addStartingForce()
    {
        float x = Random.value < 0.5f ? -1f : 1f; //less than half, go negative. Greater than half, go positive
        float y = Random.value < 0.5f ? Random.Range(-1f, -0.5f) : Random.Range(0.5f, 1f);

        Vector2 direction = new Vector2(x, y);
        rbBall.AddForce(direction * speedBall);
    }

    public void addforce(Vector2 force)
    {
        rbBall.AddForce(force);
    }

    void HeadingTowards()
    {
        Vector2 Dir = new Vector2(-50f, 0f);
        rbBall.AddForce(Dir * speedBall);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("wall"))
        {
            HeadingTowards();
        }
    }
}

Now once it bounces off a wall, it sometimes head towards my ("HeadingTowards") direction which was intended but after each bounce it didn't and the speed goes crazy fast unless I put time.deltaTime which I was told to not put it on addforce.

enter image description here

\$\endgroup\$
4
  • \$\begingroup\$ Am I understanding that you always want the ball to bounce left when it hits the wall, no matter what its incident angle was? \$\endgroup\$
    – DMGregory
    May 23 at 12:43
  • \$\begingroup\$ like when it goes more positive, it will bounce to the right. But when it goes negative, it will bounce to that specific direction \$\endgroup\$ May 23 at 13:04
  • \$\begingroup\$ Hmm... it might help if you include a diagram showing a few different incoming bounces, and what you want the outgoing bounce to look like in each case. I'm not confident I understand your goal from the text description so far. \$\endgroup\$
    – DMGregory
    May 23 at 13:45
  • \$\begingroup\$ ok have edited to post a pic for example haha. Basically I want that object to bounce and no matter where it collides with, it will bounce off and goes right onto that one position. \$\endgroup\$ May 23 at 13:56

1 Answer 1

1
\$\begingroup\$

It sounds like you just want to bend the velocity to aim at a specific position, not add a force. So, don't add a force, just set the velocity.

void HeadingTowards(Vector2 targetPosition)
{
    Vector2 Dir = (targetPosition - rbBall.position).normalized;
    rbBall.velocity(Dir * speedBall);
}
\$\endgroup\$
1
  • \$\begingroup\$ thank you so much! \$\endgroup\$ May 23 at 15:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .