I am working on creating a mini vector graphics ping pong table, as described in this previous post: Trying to use 3D vectors for a 2D ping pong game
Currently, the stage I am at, I am trying to make it so that when the ball exceeds the X bounds of the table, it will reflect backwards and at a new target: a random x,y,z position on the opponent's side of the table.
Trying to use this post as a starting point: How can I launch a GameObject at a target if I am given everything except for its launch angle? I have attempted to adapt some of that example code in my program, but I am not quite getting the desired results.
** updated code **
update: function(paceFactor) {
this.ball.pos3D.x += this.ball.vel.x * paceFactor;
this.ball.pos3D.y += this.ball.vel.y * paceFactor;
this.ball.pos3D.z += this.ball.vel.z * paceFactor;
this.ball.vel.y += this.gravity * paceFactor;
if (!this.stop && Math.abs(this.ball.pos3D.x) > 15) {
this.stop = true; // for testing to prevent velocity from getting changed due to bad values returned from velocityForNextTarget()
var modifier = this.ball.pos3D.x < 0 ? 1 : -1;
var velocity = this.velocityForNextTarget(modifier);
this.ball.vel.x += velocity.x;
this.ball.vel.y += velocity.y;
this.ball.vel.z += velocity.z;
}
if (this.ball.pos3D.y >= 0) {
this.ball.vel.y *= -1;
this.ball.pos3D.y -= this.ball.pos3D.y;
}
this.convert3Dto2D();
},
velocityForNextTarget: function(modifier) {
var targetX = 5 * modifier;
var targetY = 0;
var targetZ = 0;
var deltaX = this.ball.pos3D.x - targetX;
var deltaY = this.ball.pos3D.y - targetY;
var deltaZ = this.ball.pos3D.z - targetZ;
var sqrMagnitude = (deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ);
var speed = Math.sqrt((this.ball.pos3D.x * this.ball.pos3D.x) + (this.ball.pos3D.y * this.ball.pos3D.y) + (this.ball.pos3D.z * this.ball.pos3D.z));
var gSquared = this.gravity * this.gravity;
var b = speed * speed + (deltaY * this.gravity);
var discriminant = (b * b) - (gSquared * sqrMagnitude);
var discRoot = Math.sqrt(discriminant);
var t = Math.sqrt((b - discRoot) * 2 / gSquared);
return {
x: deltaX / t * t / 2,
y: deltaY / t - this.gravity * t / 2,
z: deltaZ / t * t / 2,
};
},
So what I am trying to do is make it so that when the ball reaches the location of a player, it will target the center of the opponent's side of the table, and the ball will move there, and right now this code is making the ball rapidly jump off the screen as soon as it hits the x bounds, and I am not sure what I am doing wrong with the math in velocityForNextTarget()...
I should also mention that gravity is just a constant that I am only adding to my Y velocity so far. I am not sure if that's "right" ?