3

Как можно рассчитать координаты и скорость у 2 круглых объектов после столкновения?

Когда шары столкнутся я расчитал, а что делать дальше - я не знаю.

Хочу сделать как здесь, но не совсем понимаю, что происходит:

/*
Copyright (c) 2013 dissimulate at codepen

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/

document.getElementById('close').onmousedown = function(e) {
  e.preventDefault();
  document.getElementById('info').style.display = 'none';
  return false;
};

var NUM_BALLS = 130,
    DAMPING = 0.7,
    GRAVITY = 0.6,
    MOUSE_SIZE = 50,
    SPEED = 1;

var canvas, ctx, TWO_PI = Math.PI * 2, balls = [], mouse = {down:false,x:0,y:0};

window.requestAnimFrame =
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
        window.setTimeout(callback, 1000 / 60);
    };

var Ball = function(x, y, radius) {

    this.x = x;
    this.y = y;

    this.px = x;
    this.py = y;

    this.fx = 0;
    this.fy = 0;

    this.radius = radius;
};

Ball.prototype.apply_force = function(delta) {

    delta *= delta;

    this.fy += GRAVITY;

    this.x += this.fx * delta;
    this.y += this.fy * delta;

    this.fx = this.fy = 0;
};

Ball.prototype.verlet = function() {

    var nx = (this.x * 2) - this.px;
    var ny = (this.y * 2) - this.py;

    this.px = this.x;
    this.py = this.y;

    this.x = nx;
    this.y = ny;
};

Ball.prototype.draw = function(ctx) {

    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, TWO_PI);
    ctx.fill();
};

//---------------------------------------

var resolve_collisions = function(ip) {

    var i = balls.length;

    while (i--) {

        var ball_1 = balls[i];

        if (mouse.down) {

            var diff_x = ball_1.x - mouse.x;
            var diff_y = ball_1.y - mouse.y;
            var dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
            var real_dist = dist - (ball_1.radius + MOUSE_SIZE);

            if (real_dist < 0) {

                var depth_x = diff_x * (real_dist / dist);
                var depth_y = diff_y * (real_dist / dist);

                ball_1.x -= depth_x * 0.005;
                ball_1.y -= depth_y * 0.005;
            }
        }

        var n = balls.length;

        while (n--) {

            if (n == i) continue;
          
            var ball_2 = balls[n];

            var diff_x = ball_1.x - ball_2.x;
            var diff_y = ball_1.y - ball_2.y;

            var length    = diff_x * diff_x + diff_y * diff_y;
            var dist      = Math.sqrt(length);
            var real_dist = dist - (ball_1.radius + ball_2.radius);

            if (real_dist < 0) {

                var vel_x1 = ball_1.x - ball_1.px;
                var vel_y1 = ball_1.y - ball_1.py;
                var vel_x2 = ball_2.x - ball_2.px;
                var vel_y2 = ball_2.y - ball_2.py;

                var depth_x = diff_x * (real_dist / dist);
                var depth_y = diff_y * (real_dist / dist);

                ball_1.x -= depth_x * 0.5;
                ball_1.y -= depth_y * 0.5;
                
                ball_2.x += depth_x * 0.5;
                ball_2.y += depth_y * 0.5;

                if (ip) {

                    var pr1 = DAMPING * (diff_x*vel_x1+diff_y*vel_y1) / length,
                        pr2 = DAMPING * (diff_x*vel_x2+diff_y*vel_y2) / length;

                    vel_x1 += pr2 * diff_x - pr1 * diff_x;
                    vel_x2 += pr1 * diff_x - pr2 * diff_x;

                    vel_y1 += pr2 * diff_y - pr1 * diff_y;
                    vel_y2 += pr1 * diff_y - pr2 * diff_y;

                    ball_1.px = ball_1.x - vel_x1;
                    ball_1.py = ball_1.y - vel_y1;

                    ball_2.px = ball_2.x - vel_x2;
                    ball_2.py = ball_2.y - vel_y2;
                }
            }
        }
    }
};

var check_walls = function() {

    var i = balls.length;

    while (i--) {

        var ball = balls[i];

        if (ball.x < ball.radius) {

            var vel_x = ball.px - ball.x;
            ball.x = ball.radius;
            ball.px = ball.x - vel_x * DAMPING;

        } else if (ball.x + ball.radius > canvas.width) {

            var vel_x = ball.px - ball.x;
            ball.x = canvas.width - ball.radius;
            ball.px = ball.x - vel_x * DAMPING;
        }

        if (ball.y < ball.radius) {

            var vel_y = ball.py - ball.y;
            ball.y = ball.radius;
            ball.py = ball.y - vel_y * DAMPING;

        } else if (ball.y + ball.radius > canvas.height) {

            var vel_y = ball.py - ball.y;
            ball.y = canvas.height - ball.radius;
            ball.py = ball.y - vel_y * DAMPING;
        }
    }
};

var update = function() {

    //var time = new Date().getTime();

    var iter = 6;

    var delta = SPEED / iter;

    while (iter--) {

        var i = balls.length;

        while (i--) {

            balls[i].apply_force(delta);
            balls[i].verlet();
        }

        resolve_collisions();
        check_walls();

        var i = balls.length;
        while (i--) balls[i].verlet();

        resolve_collisions(1);
        check_walls();
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = 'rgba(27,155,244,0.3)';

    var i = balls.length;
    while (i--) balls[i].draw(ctx);

    if (mouse.down) {

        ctx.fillStyle   = 'rgba(0,0,0,0.1)';
        ctx.strokeStyle = 'rgba(0,0,0,0.2)';

        ctx.beginPath();
        ctx.arc(mouse.x, mouse.y, MOUSE_SIZE, 0, TWO_PI);
        ctx.fill();
        ctx.stroke();
    }

    requestAnimFrame(update);

    //console.log(new Date().getTime() - time);
};

var add_ball = function(x, y, r) {

    var x = x || Math.random() * (canvas.width - 60) + 30,
        y = y || Math.random() * (canvas.height - 60) + 30,
        r = r || 10 + Math.random() * 20,
        s = true,
        i = balls.length;

    while (i--) {

        var ball = balls[i];
        var diff_x = ball.x - x;
        var diff_y = ball.y - y;
        var dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);

        if (dist < ball.radius + r) {
            s = false;
            break;
        }
    }

    if (s) balls.push(new Ball(x, y, r));
};

window.onload = function() {

    canvas = document.getElementById('c');
    ctx = canvas.getContext('2d');

    canvas.width = 1000;
    canvas.height = 360;
    
    while (NUM_BALLS--) add_ball();

    canvas.onmousedown = function(e) {

        if (e.which == 1) {

            add_ball(mouse.x, mouse.y);

        } else if (e.which == 3) {

            mouse.down = true;
            document.body.style.cursor = 'none';
        }

        e.preventDefault();
    };

    canvas.onmouseup = function(e) {

        if (e.which == 3) {

            mouse.down = false;
            document.body.style.cursor = 'default';
        }

        e.preventDefault();
    };

    canvas.onmousemove = function(e) {

        var rect = this.getBoundingClientRect();
        mouse.x = e.clientX - rect.left;
        mouse.y = e.clientY - rect.top;
    };
  
    canvas.onmouseout = function(e) {
      
        mouse.down = false;
        document.body.style.cursor = 'default';
    };

    canvas.oncontextmenu = function(e) {

        e.preventDefault();
        return false;
    };

    update();
};
* {
	margin: 0;
	padding: 0;
}

body,html {
	background: #FFF8E7;
	width: 100%;
	height: 100%;
}

canvas {
	background: #FFF8E7;
	width: 1000px;
	height: 360px;
	margin: 0 auto;
	display: block;
	border: 1px dashed #aaa;
	border-top: none;
}

#info {
	position: absolute;
	top: 0;
	left: 0;
	padding-bottom: 30px;
	background: rgba(0,0,0,0.4);
	border: 1px solid rgba(0,0,0,0.4);
}

#info #close {
	position: absolute;
	width: 17px;
	height: 20px;
	right: -17px;
	top: -2px;
	line-height: 20px;
	text-align: center;
	color: #fff;
	font-family: Arial, sans-serif;
	background: rgba(0,0,0,0.6);
	text-decoration: none;
	border-bottom-right-radius: 5px;
}

#info .title {
	width: 100%;
	height: 40px;
	line-height: 40px;
	text-align: center;
	color: #aaa;
	font-family: Arial, sans-serif;
	font-size: 18px;
	background: rgba(0,0,0,0.4);
}

#info .footer {
	width: 100%;
	height: 30px;
	position: absolute;
	bottom: 0;
	line-height: 30px;
	text-align: center;
	color: #ADE1F7;
	font-family: Arial, sans-serif;
	font-size: 16px;
	background: rgba(0,0,0,0.2);
	text-decoration: none;
}

#info .item {
	line-height: 40px;
	color: #333;
	font-family: Arial, sans-serif;
	font-size: 16px;
	margin: 0 10px;
}
<canvas id="c"></canvas>
<div id="info">
  <a id="close" href="">
  &#215;
  </a>
  <div class="title">
  Ball Physics
  </div>
  <div class="item">
  &#8226; Right click to interact.
  </div>
  <div class="item">
  &#8226; Left click to add a new ball.
  </div>
</div>

Пробовал чтобы они просто обменивались скоростями, но получается, что они как будто отталкиваются от стенки, а должны менять скорость и координаты в зависимости от угла падения, не прилипали и т. д.

Мой код:

canvas.height = innerHeight
canvas.width = innerWidth

document.body.style.overflow = 'hidden'
document.body.style.margin = 0

ctx = canvas.getContext('2d')

balls = []
gravPower = 0.7
c = 0

mouse = {
	x: 0,
	y: 0
}

Ball = function(x,y,r,c){
	return {
		x,
		y,
		r,
		c:'rgb('+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+')',
		vx: 4,
		vy: 0,
		born: Date.now()
	}
}

grav = function(ball){
    //столкновение с другими шарами
    //vx,vy - скорость
	for (o = balls.length - 1; o >= 0; o--) {
		if(o == i){
			continue
		}

		var ball2 = balls[o]
		dx =ball.x-ball2.x
		dy = ball.y-ball2.y
		d = Math.sqrt(dx*dx+dy*dy)

		if(d < ball.r + ball2.r){
			//шары столкнулись
			ball.c = 'red'          
		}
	}
  
    //столкновение со стенами
	if(checkRightWall(ball) || checkLeftWall(ball)){
		if(checkRightWall(ball)){
			ball.x = canvas.width - ball.r
		}
		if(checkLeftWall(ball)){
			ball.x = 0 + ball.r
		}
		ball.vx *= -1
	} else {
		ball.x += ball.vx
	}
	if(checkDownWall(ball) || checkUpWall(ball)){
		if(checkDownWall(ball)){    
			if(ball.vy < gravPower * 4){
				ball.vy = 0
			}
			ball.y = canvas.height - ball.r
		}
		if(checkUpWall(ball)){
			ball.y = 0 + ball.r + 1
		}
		ball.vy *= -0.7
		ball.vx *= 0.7
	} else {
		ball.y += ball.vy
		ball.vy += gravPower
	}
}

draw = function(ball){
	ctx.beginPath()
	ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI*2)
	ctx.fillStyle = ball.c
	ctx.fill()
	ctx.stroke()
	ctx.closePath()
  

	if(checkDownWall(ball)){
		ctx.fillStyle = 'black'
		ctx.fillRect(ball.x,ball.y,1,1)
	}
}
step = function(){
	ctx.clearRect(0,0,canvas.width,canvas.height)
	for (i = balls.length - 1; i >= 0; i--) {
		var ball = balls[i]
		if(balls.length > 170){
			balls.splice(0,1)
		}
		grav(ball)
		draw(ball)
	}
  	ctx.fillText('Click to add Ball',60,60)
	requestAnimationFrame(step)
}

checkRightWall = function(ball){
	return ball.x + ball.r + ball.vx >= canvas.width
}
checkLeftWall = function(ball){
	return ball.x - ball.r + ball.vx <= 0
}
checkDownWall = function(ball){
	return ball.y + ball.r + ball.vy >= canvas.height 
}
checkUpWall = function(ball){
	return ball.y - ball.r + ball.vy <= 0 
}

balls.push(Ball(50,70,40))
balls.push(Ball(50,300,40))

document.onclick = function(e){
	balls.push(Ball(e.pageX,e.pageY,40))
}

document.onmousemove = function(e){
	mouse.x = e.pageX
	mouse.y = e.pageY
}
document.onkeydown = step
requestAnimationFrame(step)
<canvas id="canvas"></canvas>

3
  • 1
    Закон сохранения импульса, закон сохранения энергии...
    – Harry
    27 сен 2017 в 15:04
  • 1
    Читайте вот ru.stackoverflow.com/questions/643123/…
    – nick_n_a
    27 сен 2017 в 15:07
  • 1
    Если интересно, то советую найти и почитать книгу Джоб Макар - "Секреты разработки игр в Macromedia Flash MX" + CD бонус, 2004 г.. Она написана для Flash MX (ActionScript 2.0), но так как это языки близнецы на одном EcmaScript, все примеры можно разобрать и повторить для JS. Там есть нужные главы "тригонометрия", "основы физики", "определение столкновений" и "реакция на столкновения" с картинками, а так же примеры для игр "Пинбол" и "9 Шаров" (бильярд).
    – Alex Krass
    28 сен 2017 в 9:43

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Посмотрите другие вопросы с метками или задайте свой вопрос.