Ball bounces too much from AI collision
I want to create a simple pong game with an AI as an enemy. Everything is good until I add the AI movement script to the racket. The problem is as soon as the ball hits the racket it behavs like it has a bounciness 1000 or it got 1000 force. So the ball speed gets suddenly too much.
Here is the code: using UnityEngine; using System.Collections;
public class AIMovement : MonoBehaviour {
public GameObject ball;
public float speed;
private Rigidbody2D rb2D;
// Use this for initialization
void Start () {
rb2D = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void FixedUpdate () {
Vector2 move = new Vector2 (ball.transform.position.x, 0.0f);
rb2D.MovePosition (move);
}
}
If I add code from manual the bounce behaves like it should but the movement of the racket behaves like it has 3000 ping.
rb2D.MovePosition(rb2D.position + velocity * Time.fixedDeltaTime);
Answer by Levike · Dec 20, 2015 at 08:58 AM
So I found a workaround for this. Here is the code. Speed is for making the AI beatable.
using UnityEngine;
using System.Collections;
public class AIMovement : MonoBehaviour {
public Transform ball;
private float speed;
public float distance;
private Rigidbody2D rb2D;
void Start(){
rb2D = GetComponent<Rigidbody2D> ();
}
void FixedUpdate(){
speed = Time.fixedDeltaTime * 40;
if ((transform.position.y - ball.position.y) >= distance) {
rb2D.MovePosition(new Vector2(ball.position.x, 0.0f) * speed);
}
}
}
Basically I had to put the MovePosition to an if statement and the minimum distance must be set to 0.6. Below that the weird thing is happening;
I still don't know why it happens tho.
Answer by Veerababu.g · Dec 19, 2015 at 12:30 PM
the force is adding contentiously........ it has to add only one time whenever you call
There is no force on the ball only at Start() with a delay of 3 sec.
GetComponent ().velocity = 20;
The 1000 force is just explaining the bug. How the ball behaves. As soon as it touch the AI racket the first time it bounces back with a lot of speed. If I remove the $$anonymous$$ovePosition then everything is good except the AI racket is not moving.
Ohh you meant the second code. Yes but the velocity here is the position of the ball that needs to be updated every frame.
Your answer
Follow this Question
Related Questions
How to use Rigidbody2D.MovePosition to move a kinematic object around looping waypoints? 1 Answer
Rigidbody2D doesn't fall correctly when using MovePosition to move it horizontally 0 Answers
Move a RigidBody with MovePosition up and down 1 Answer
How do I prevent a rigidbody2D from falling through the ground? 0 Answers