movimiento_parabolico(distancia, vx,vy);

Publicado por dixon, Mayo 28, 2022, 06:14:49 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

dixon

Autor del script: Reyes Dávila (Dixon)
Nombre del script: movimiento_parabolico(distancia,altura,velocidad horizontal);
Breve descripción de su función: Aplica movimiento parabólico a un objeto estableciendo solo la distancia, la altura y la velocidad.
Versiones usadas: Game maker 4  y game maker html5. Debe funcionar en todas las demás versiones superiores a gmk 4.
Versión del script: 2  (se añade argumento altura para establecer la altura màxima a alcanzar)


Html5: Aquí podrán ver el código en funcionamiento.



[gml]
//movimiento_parabolico(distancia,altura,velocidad horizontal)
//Colocar en evento create: movimiento_parabolico_create=1;
//distancia: es la distancia que recorrerá el objeto;
//altura: es la altura máxima a alcanzar;
//velocidad horizontal: es la velocidad horizontal que puede ser positiva o negativa;
//serial del script: A12HRJ36;

if(movimiento_parabolico_create)
{
movimiento_parabolico_create=0;
distancia_A12HRJ36=abs(argument0);
altura_A12HRJ36=abs(argument1);
velocidad_A12HRJ36=argument2;
xfinal_A12HRJ36=x+distancia_A12HRJ36;

direction270=0;

gravedad_A12HRJ36=0;
y2_A12HRJ36=y;
continuar_A12HRJ36=1;
while(y2_A12HRJ36>(y-altura_A12HRJ36) and (continuar_A12HRJ36))
{
gravedad_A12HRJ36+=0.1;
x2_A12HRJ36=x;
y2_A12HRJ36=y;
for(i_A12HRJ36=0;i_A12HRJ36<=(distancia_A12HRJ36/2) and continuar_A12HRJ36;i_A12HRJ36+=1)
{
x2_A12HRJ36+=velocidad_A12HRJ36;
direction=90+(distancia_A12HRJ36-(xfinal_A12HRJ36-x2_A12HRJ36))*180/distancia_A12HRJ36;
y2_A12HRJ36-=gravedad_A12HRJ36*sin(direction*pi/180);
if(y2_A12HRJ36<=y-altura_A12HRJ36){continuar_A12HRJ36=0}
}
}

}

x+=velocidad_A12HRJ36;
if(direction270<270){direction=90+(distancia_A12HRJ36-(xfinal_A12HRJ36-x))*180/distancia_A12HRJ36;direction270=90+abs((distancia_A12HRJ36-(xfinal_A12HRJ36-x))*180/distancia_A12HRJ36)};
y=y-gravedad_A12HRJ36*sin(direction*pi/180);

[/gml]




Modo de uso
1. Crea un nuevo script y pégale el código que se está entregando.
2. Colocar en el evento create del objeto a mover (ejemplo: la pelota, el proyectil):
movimiento_parabolico_create=1;

3. Colocar en el evento step o paso del objeto a mover:
movimiento_parabolico(200,150,10);





Detalles de la función:
movimiento_parabolico(distancia,altura,velocidad horizontal): en distancia colocar la distancia a alcanzar, en altura colocar la altura máxima que alcanzará el objeto y en velocidad colocar la velocidad de movimiento horizontal, para mover a la izquierda usar velocidades negativas.

Imagen de referencia:



Ejemplo:
movimiento_parabolico(50,50,1);


Mejoras a futuro:
Se requiere un script que controle el movimiento parabólico aplicando las reglas generales de la física.

Más información:
Este script lo he creado principalmente para nuestro amigo Jeffrey Faper , el cual se mantiene en constante programación y en algún momento nos mostrará alguno de sus proyectos. Le deseo que tenga éxito en su proyecto y que sus métodos sirvan de aprendizaje para todos nosotros.

El archivo index empleado en el juego de la parabola es el siguiente:
<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Generated by GameMaker:HTML5 http://http://www.yoyogames.com/gamemaker/html5 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge" >
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name ="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
        <meta charset="utf-8"/>

        <!-- Set the title bar of the page -->
        <title>Game Maker HTML 5</title>

        <!-- Set the background colour of the document -->
        <style>
            body {
              background: #222;
              color:#cccccc;
            }
            canvas {
                      image-rendering: optimizeSpeed;
                      -webkit-interpolation-mode: nearest-neighbor;
            }
        </style>
    </head>

    <body>
            <!-- Create the canvas element the game draws to -->
            <canvas id="canvas" width="400" height="300">
               <p>Your browser doesn't support HTML5 canvas.</p>
            </canvas>

        <!-- Run the game code -->
        <script type="text/javascript" src="html5game/gmk.js?FWFZB=2052234977"></script>






















	<div id="botonA"></div>
	<div id="botonB">F</div>


	<style>
	body
	{
	   text-align: center;
	}

	#botonA
	{
	position:absolute;
	top: 5vh;
	left: 5vw;
	width: 90vw;
	height: 90vh;
	}

	#botonB
	{
   	 -webkit-user-select: none;
    	-moz-user-select: none;
   	 -khtml-user-select: none;
   	 -ms-user-select:none;

	position:absolute;
	top: 5px;
	right: 5px;
	font-size: 1em;
	border-radius: 10%;
	border: 1px solid white;
	width: 2em;
	}

	</style>



	<script>

	var canvas = document.getElementById("canvas");
        var canvasProporcion = canvas.width/canvas.height;

	var ventana={
	ancho: window.innerWidth,
	alto: window.innerHeight,
	orientacion: "landscape"
	}

	var botonA_Elemento = document.getElementById("botonA");
var botonB_Elemento = document.getElementById("botonB");

var touchDevice = ('ontouchstart' in document.documentElement);

if(touchDevice == true)
{
  botonA_Elemento.addEventListener("touchstart", function(){funcionBoton(65,"pulsar")});
  botonA_Elemento.addEventListener("touchend", function(){funcionBoton(65,"soltar")});
  botonA_Elemento.addEventListener("touchleave", function(){funcionBoton(65,"soltar")});

  botonB_Elemento.addEventListener("touchstart", function(){toggleFullScreen()});
}
else
{
  botonA_Elemento.addEventListener("mousedown", function(){funcionBoton(65,"pulsar")});
  botonA_Elemento.addEventListener("mouseup", function(){funcionBoton(65,"soltar")});
  botonA_Elemento.addEventListener("mouseleave", function(){funcionBoton(65,"soltar")});

  botonB_Elemento.addEventListener("mousedown", function(){toggleFullScreen()});
}


/////////////////Funcion de botones
////////////////SIMULANDO TECLADO
////////////////////////////////////////////////////////////////////////////////
function funcionBoton(codigoBoton, accionBoton){
    //alert(codigoBoton);
	var eventObj_izquierda = document.createEventObject ?
    	document.createEventObject() : document.createEvent("Events");
	eventObj_izquierda.keyCode = codigoBoton;
	eventObj_izquierda.which = codigoBoton;
	eventObj_izquierda.key=' ';
	eventObj_izquierda.code='Space';
	if(accionBoton == "pulsar")
		{
		if(eventObj_izquierda.initEvent){eventObj_izquierda.initEvent("keydown", true, true)}
		document.dispatchEvent ? document.dispatchEvent(eventObj_izquierda) : document.fireEvent("onkeydown", eventObj_izquierda);
		}
	if(accionBoton == "soltar")
		{
		if(eventObj_izquierda.initEvent){eventObj_izquierda.initEvent("keyup", true, true)}
		document.dispatchEvent ? document.dispatchEvent(eventObj_izquierda) : document.fireEvent("onkeyup", eventObj_izquierda);
		}
	}
//////////////////////////////////////////////////////////////////////////////////


///////////////FUNCION PANTALLA COMPLETA
////////////////////////////////////////////////////////////////////////////////
function toggleFullScreen() {
  	if ((document.fullScreenElement && document.fullScreenElement !== null) ||   
   	(!document.mozFullScreen && !document.webkitIsFullScreen)) {
   	if (document.documentElement.requestFullScreen) {
   	document.documentElement.requestFullScreen();
    	} else if (document.documentElement.mozRequestFullScreen) {
	document.documentElement.mozRequestFullScreen();
	} else if (document.documentElement.webkitRequestFullScreen) {
	document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
	}
	} else {
	if (document.cancelFullScreen) {
	document.cancelFullScreen();
	} else if (document.mozCancelFullScreen) {
	document.mozCancelFullScreen();
	} else if (document.webkitCancelFullScreen) {
	document.webkitCancelFullScreen();
}}}
/////////////////////////////////////////////////////////////////////////////////


setInterval('ejecucionConstante()',1000/30);
function ejecucionConstante()
{
ventana["ancho"]=window.innerWidth;
ventana["alto"]=window.innerHeight;

var porcentajeMaximo=95;
var canvasAncho = porcentajeMaximo*ventana["ancho"]/100;
var canvasAlto = canvasAncho/canvasProporcion;
var canvasAltoMaximo = porcentajeMaximo*ventana["alto"]/100;

while(canvasAlto>canvasAltoMaximo)
{
canvasAncho -=1;
var canvasAlto = canvasAncho/canvasProporcion;
}

canvas.style.width=`${canvasAncho}px`;


}//fin function ejecucionConstante()
</script>































    </body>
</html>



Bay...

brunoxzx

El script está perfecto para una IA que lance objetos en forma parabólica, tan solo calculas la distancia horizontal al objetivo y ya, si quieres que esquive un obstáculo le pones que vaya por cierta altura.

218 Visitantes, 0 Usuarios