@derasoft

Почему спавнятся лишние объекты и почему я не могу никак их отловить?

Здравствуйте.
Если вкратце - сайт представляет собой доску с кучей картинок, которые по нему можно двигать. Вот объект, который отвечает за появление картинки на странице.
const field_con = {
	fig_list: [],
	addFigure(obj){	
		if (obj.id != undefined) {
			this.fig_list[obj.id] = document.createElement('img');
			that = this.fig_list[obj.id];
		} else {
			this.fig_list[this.fig_list.length] = document.createElement('img');
			that = this.fig_list[this.fig_list.length-1];
			that.id = this.fig_list.length-1;
		}
		that.orig = obj;
		that.name = obj.name;
		that.title = obj.name;
		that.src = "http://127.0.0.1:8000/static/" + obj.src;
		that.orig.rota = (that.orig.rota == undefined) ? (0) : that.orig.rota;
		that.eventAnchor = 'figure';
		that.x_cord = obj.x;
		that.y_cord = obj.y;
		console.log(obj.x);
		that.style.top = that.y_cord + 'px';
		that.style.left = that.x_cord + 'px';
		that.style.position = 'absolute';
		that.style.transform = `rotate(${that.orig.rota}deg)`;
		that.bound_fig = obj.bound_fig;
		if (that.bound_fig != undefined) that.bound_fig.onField = this.fig_list[that.id];
		that.bound_unit = obj.bound_unit;
		that.onmousedown = mouseDownWrapperUnit;
		if (that.bound_unit != undefined) that.onmouseover =  highlight_unit;
		that.onmouseout = highlight_unit_stop;
		document.body.append(that);
		return that;
	},
}


У меня заранее подгружено одно изображение, которое имеет немного замороченную, но функцию Drag'nDrop'а (вот его код):
function dragndrop(event, target) { 
	that = target;
	that.ondragstart = function() {return false;};
	that.style.position = 'absolute';
	that.style.zIndex = 1000;
	document.body.append(that);
	corr_x = event.pageX - that.getBoundingClientRect().x;
	corr_y = event.pageY - that.getBoundingClientRect().y;
	moveAt(event.pageX, event.pageY);
	if (game_con.unitMoverActive == true) {
		for (c of game_con.initials)
			if (c.whom == that) {
				startpoint = c;
			}
	};
	function moveAt(pageX, pageY) {
		that.x_cord = (pageX - corr_x);
		that.style.left = that.x_cord + 'px';
		that.y_cord = (pageY - corr_y);
		that.style.top = that.y_cord + 'px';
		findAngle(200, 200, that.x_cord, that.y_cord);
	}
	function onMouseMove(event) {
		if ((game_con.unitMoverActive == false)||(rangeMeasure(that.initialMovementX, that.initialMovementY, that.x_cord, that.y_cord)<that.bound_unit.move)) {
			moveAt(event.pageX, event.pageY, that);
		}
	}
	document.addEventListener('mousemove', onMouseMove);
	that.onwheel = wheel_rotate;
	that.onmouseup = function() {
		document.removeEventListener('mousemove', onMouseMove);
		that.style.zIndex = 500;
		that.onmouseup = null;
		that.onwheel = null;
	};
};

Недавно, я попытался реализовать функцию, которая должна определять угол одного объекта относительно другого (findAngle), и в качестве теста решил немного её расширить - теперь она должна рисовать след за перетаскиваемым объектом, но если объект вышел за определённый радиус, то след "упрётся" в невидимую стену и не сможет её покинуть. Вот код функции:
function findAngle(x0, y0, x, y) {
	r = rangeMeasure(x0, y0, x, y);
	cx = Math.acos((x - x0) / r);
	cy = Math.asin((y - y0) / r);
	// console.log(Math.trunc(cx*57,2958), ' ', Math.trunc(cy*57,2958));
	if (r>100) {
		r = 100;
	};
	zx = r * Math.cos(cx) + x0;
	zy = r * Math.sin(cy) + y0;
	obj = {
		src: 'dot.png',
		x: zx,
		y: zy,
	};
	console.log(obj.x, ' ', obj.y);
	if (r>=100) {
		rra = field_con.addFigure(obj);
		console.log(rra);
		if (rangeMeasure(200, 200, rra.x, rra.y)>r) rra.remove();
	}
}

Однако, появляется проблема. Сам по себе код работает, но только появляется сразу два следа - "правильный", упёршийся в "стену", и тот, который продолжает следовать за картинкой:
64ea10ae14438425502344.png
Попытки отследить, откуда возникают призрачные точки успехом не увенчались: Если закоментировать вызов addFigure в функции findAngle, то перестают рисоваться вообще любые следы, а попытка отследить возникновение этих точек не приводит к чему-либо осмысленному (смотреть на точку с id 4):
64ea115e374cb814375818.png
Собственно, а откуда вообще берутся эти призрачные точки?
Если необходимо, то вот полный код скрипта: https://pastebin.com/pKsNnKjN
  • Вопрос задан
  • 81 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы