Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Blackbeard

Ajuda com aprendizado em javascript - babylonjs - webpack. Classe náo compila com variaveis da classe.

Recommended Posts

Ola, boa tarde.

Estou tentando montar um projeto de game de cartas em webgl usando babylonjs+webpack. O problema é que na hora de compilar uma classe, o webpack não esta deixando se eu declaro variaveis da classe logo acima do construtor, retornando o seguinte erro:

Erro:

RROR in ./src/game.js 33:9
Module parse failed: Unexpected token (33:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export default class Game {
|
>     scene;
|     clickedButtonBJ;
|
 @ ./src/index.js 3:0-29 17:15-19


Segue meus arquivos de configuração do webpack e do package.json e o código especifico da classe game.js.

 

Webpack.config.js

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      inject: true,
      template: path.resolve(__dirname, 'src', 'index.html'),
    }),
  ],
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
            presets: ['es2015']
        }
    }
    ]
  }
}

 

 

package.json:

 

{
  "name": "synthgaming.tech",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "run-dev": "npx webpack-dev-server",
    "build": "webpack --config=webpack.config.prod.js",
    "build-dev": "webpack --config=webpack.config.dev.js",
    "start": "webpack-dev-server --config=webpack.config.dev.js --open"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babylonjs/core": "^4.1.0",
    "@babylonjs/gui": "^4.1.0",
    "@babylonjs/inspector": "^4.1.0",
    "@babylonjs/loaders": "^4.1.0",
    "@babylonjs/materials": "^4.1.0",
    "@babylonjs/post-processes": "^4.1.0",
    "@babylonjs/procedural-textures": "^4.1.0",
    "@babylonjs/serializers": "^4.1.0",
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^4.2.0",
    "ts-loader": "^7.0.0",
    "typescript": "^3.8.3",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0"
  }
}


game.js:
 

import {
    Vector3, Color3
} from "@babylonjs/core/Maths/math";
import {
    ArcRotateCamera
} from "@babylonjs/core/Cameras/arcRotateCamera";
import {
    HemisphericLight
} from "@babylonjs/core/Lights/hemisphericLight";
import {
    Mesh
} from "@babylonjs/core/Meshes/mesh";

import {
    GridMaterial
} from "@babylonjs/materials/grid";

import {
    Sound, HighlightLayer
} from "@babylonjs/core"

import { 
    Image, Control, AdvancedDynamicTexture, Button, TextBlock
} from "@babylonjs/gui";

import { 
    Scene 
} from "@babylonjs/core";


export default class Game {

    scene;
    clickedButtonBJ;

    constructor(){
        // this.scene = _scene;
        this.clickedButtonBJ = false;
    }

    

   

    Start(scene) {
        

        var camera = new ArcRotateCamera("gameCamera", 0,0,0, new Vector3(0, 5, -10), scene);
        camera.setPosition(new Vector3(0,1,-40));
        camera.setTarget(Vector3.Zero());

        var light = new HemisphericLight("light1", new Vector3(0, 1, 0), scene);
        light.intensity = 0.49;

             
        var tetraMaterial = new GridMaterial("Tetragrid" , scene);
            
        var tetra = new Mesh.CreatePolyhedron("tetra", {type: 0, size: 3}, scene);
    
        tetra.position.y = 4.8;
        tetra.position.z = -15;
        tetra.rotation.z = Math.PI/2;
        tetra.rotation.x = 4*Math.PI/3;
    
        var hl1 = new HighlightLayer("hl1", scene);
        hl1.addMesh(tetra, Color3.Magenta());
        
        tetra.material = tetraMaterial;
    
        var groundMaterial = new GridMaterial("grid", scene);
        groundMaterial.lineColor = new Color3(2,2,4);
      
        var ground = new Mesh.CreateGround("ground1", 600, 600, 3, scene);
        ground.material = groundMaterial;
    
        var advancedTexture = AdvancedDynamicTexture.CreateFullscreenUI("UI", scene);
    
        var titleImage = new Image("title","../res/Title.png");
        titleImage.width = "800px";
        titleImage.height = "300px";
        titleImage.top = "-50px";
        titleImage.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER;
        titleImage.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP;
        advancedTexture.addControl(titleImage);
    
        var backMusic = new Sound ("Music", "../res/raia-bellzy.wav",scene, null, {
            loop: true,
            autoplay: true 
            });

        var alpha = 0;
        scene.registerBeforeRender(() => {

            

            tetra.rotation.y += 0.005;

            alpha += 0.03;
            hl1.blurHorizontalSize = 0.3 + Math.cos(alpha) * 0.6 + 0.6;
            hl1.blurVerticalSize = 0.3 + Math.sin(alpha / 3) * 0.6 + 0.6;
        });

    }

    createNewScene(_engine) {
        var scene = new Scene(_engine);
        scene.autoClear = false;

        var camera = new ArcRotateCamera("gameCamera", 0,0,0, new Vector3(0, 5, -10), scene);
        camera.setPosition(new Vector3(0,1,-40));
        camera.setTarget(Vector3.Zero());

        var light = new HemisphericLight("light1", new Vector3(0, 1, 0), scene);
        light.intensity = 0.49;

        return scene;
    }

    disposeScene(_scene) {
        _scene.dispose();
    }

    createPrimaryMenu(_scene) {
        
        var advancedTexture =  new AdvancedDynamicTexture.CreateFullscreenUI("PrimaryUI", _scene);
       
        var buttonBJ = Button.CreateSimpleButton("butBJ","BlackJack");
        buttonBJ.width = "250px";
        buttonBJ.height = "80px";
        buttonBJ.color = "Black";
        buttonBJ.cornerRadius = 3;
        buttonBJ.background = "magenta";
        buttonBJ.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT;
        buttonBJ.left = "50px";

        buttonBJ.onPointerMoveObservable.add(function(){
            textblock.text = "Click to Play BlackJack"
        });
        buttonBJ.onPointerOutObservable.add(function() {
            textblock.text = "";
        });
        buttonBJ.onPointerUpObservable.add(function () {

            //// 
            
            this.clickedButtonBJ = true;
            console.log("0.8");

        });
        advancedTexture.addControl(buttonBJ);
 
        var textblock = new TextBlock("textblock", "");
        textblock.width = 0.2;
        textblock.height = "40px";
        textblock.color = "White";
        advancedTexture.addControl(textblock);

    }

}

Eis a questão, Se eu removo as duas linhas:

 

scene;
clickButtonBJ;

 

o código roda e eu consigo acessar o site... no entanto, não carrega na página a titleImage e nem a musica.

Alguém pode me ajudar?

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por belann
      Olá!
       
      Estou usando o nextjs versão 15.2.3 e criei uma navbar que quando é carregado o programa aparece com a home, mas na hora de clicar na página produtos desaparece a navbar.
      A navbar esta sendo chamada no layout.tsx estou usando typescript
      e fica dessa forma
      <div>           <Navbar/>             <main>{children}</main>             </div>  
    • Por violin101
      Caros amigos, saudações.

      Estou com uma dúvida, referente cálculo de valores em tempo real.

      Tenho uma rotina, que faz o cálculo, o problema é mostrar o resultado.

      Quero mostrar o RESULTADO assim: 0,00  ou  0.00

      Abaixo posto o código.
      jQuery('input').on('keyup',function(){ //Remover ponto e trocar a virgula por ponto var m = document.getElementById("pgRest").value; while (m.indexOf(".") >= 0) { m = m.replace(".", ""); } m = m.replace(",","."); //Remover ponto e trocar a virgula por ponto var j = document.getElementById("pgDsct").value; while (j.indexOf(".") >= 0) { j = j.replace(".", ""); } j = j.replace(",","."); m = parseFloat(jQuery('#pgRest').val() != '' ? jQuery('#pgRest').val() : 0); j = parseFloat(jQuery('#pgDsct').val() != '' ? jQuery('#pgDsct').val() : 0); //Mostra o Resultado em Tempo Real jQuery('#pgTroco').val(m - j); <<=== aqui estou errando })  
       
      Grato,
       
      Cesar
       
       
    • Por violin101
      Caro amigos, saudações.

      Tenho uma tabela escrita em JS que funciona corretamente.
       
      Minha dúvida:
      - como devo fazer para quando a Tabela HTML estiver vazia, exibir o LOGO da Empresa ?

      Abaixo posto o script:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'i' ) return;// Não é Ctrl+A, portanto interrompemos o script evt.preventDefault(); //Chama a Função Calcular Qtde X Valor Venda calcvda(); var idProdutos = document.getElementById("idProdutos").value; var descricao = document.getElementById("descricao").value; var prd_unid = document.getElementById("prd_unid").value; var estoque_atual = document.getElementById("estoque_atual").value; var qtde = document.getElementById("qtde").value; var vlrunit = document.getElementById("vlrunit").value; var vlrtotals = document.getElementById("vlrtotal").value; var vlrtotal = vlrtotals.toLocaleString('pt-br', {minimumFractionDigits: 2}); if(validarConsumo(estoque_atual)){ //Chama a Modal com Alerta. $("#modal_qtdemaior").modal(); } else { if(qtde == "" || vlrunit == "" || vlrtotal == ""){ //Chama a Modal com Alerta. $("#modal_quantidade").modal(); } else { //Monta a Tabela com os Itens html = "<tr style='font-size:13px;'>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='id_prds[]' value='"+idProdutos+"'>"+idProdutos+"</td>"; html += "<td width='47%' height='10'>"+ "<input type='hidden' name='descricao[]' value='"+descricao+"'>"+descricao+ "<input type='hidden' name='esp[]' value='"+prd_unid+"'> - ESP:"+prd_unid+ "<input type='hidden' name='estoq[]' value='"+estoque_atual+"'></td>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='qtde[]' value='"+qtde+"'>"+qtde+"</td>"; html += "<td width='12%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrunit[]' value='"+vlrunit+"'>"+vlrunit+"</td>"; html += "<td width='14%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrtotal[]' value='"+vlrtotal+"'>"+vlrtotal+"</td>"; html += "<td width='12%' height='10' style='text-align:center;'>"+ "<button type='button' class='btn btn-uvas btn-remove-produto' style='margin-right:1%; padding:1px 3px; font-size:12px;' title='Remover Item da Lista'>"+ "<span class='fa fa-minus' style='font-size:12px;'></span></button></td>"; html += "</tr>"; $("#tbventas tbody").append(html); //Função para Somar os Itens do Lançamento somar(); $("#idProdutos").val(null); $("#descricao").val(null); $("#prd_unid").val(null); $("#qtde").val(null); $("#vlrunit").val(null); $("#vlrtotal").val(null); $("#idProdutos").focus(); //Se INCLUIR NOVO produto - Limpa a Forma de Pagamento $("#pgSoma").val(null); $("#pgRest").val(null); $("#pgDsct").val(null); $("#pgTroco").val(null); $("#tbpagar tbody").empty(); }//Fim do IF-qtde }//Fim do Validar Consumo });//Fim da Função btn-agregar  
      Grato,

      Cesar
       
    • Por violin101
      Caros amigos, saudações.

      Estou com uma pequena dúvida se é possível ser realizado.

      Preciso passar 2 IDs para o Sistema executar a função, estou utilizando desta forma e gostaria de saber como faço via JS para passar os parâmetro que preciso.

      Observação:
      Dentro da TABELA utilizei 2 Forms, para passar os IDS que preciso, funcionou conforme código abaixo.
      <div class="card-body"> <table id="tab_clie" class="table table-bordered table-hover"> <thead> <tr> <th style="text-align:center; width:10%;">Pedido Nº</th> <th style="text-align:center; width:10%;">Data Pedido</th> <th style="text-align:center; width:32%;">Fornecedor</th> <th style="text-align:center; width:10%;">Status</th> <th style="text-align:center; width:5%;">Ação</th> </tr> </thead> <tbody> <?php foreach ($results as $r) { $dta_ped = date(('d/m/Y'), strtotime($r->dataPedido)); switch ($r->pd_status) { case '1': $status = '&nbsp;&nbsp;Aberto&nbsp;&nbsp;'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#000000'; //Cor: Preta break; case '2': $status = 'Atendido Total'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#086108'; //Cor: Verde break; case '3': $status = 'Atendido Parcial'; $txt = '#000000'; //Cor: Branco $cor = '#FEA118'; //Cor: Amarelo break; default: $status = 'Cancelado'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#D20101'; //Cor: Vermelho break; } echo '<tr>'; echo '<td width="10%" height="10" style="text-align:center;">'.$r->pd_numero.'</td>'; echo '<td width="10%" height="10" style="text-align:center;">'.$dta_ped.'</td>'; echo '<td width="32%" height="10" style="text-align:left;">'.$r->nome.'</td>'; echo '<td width="10%" height="10" style="text-align:left;"><span class="badge" style="color:'.$txt.'; background-color:'.$cor.'; border-color:'.$cor.'">'.$status.'</span></td>'; echo '<td width="5%" style="text-align:center;">'; ?> <div class="row"> <?php if($this->permission->checkPermission($this->session->userdata('permissao'), 'vPedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/visualizar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-warning" title="Visualizar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-search icon-white"></i></button> </form> <?php } if($this->permission->checkPermission($this->session->userdata('permissao'), 'ePedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/editar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-primary" title="Editar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-edit icon-white"></i></button> </form> <?php } ?> </div> <?php echo '</td>'; echo '</tr>'; } ?> </tbody> </table> </div>
      Grato,

      Cesar.
    • Por belann
      Olá!
       
      Estou usando o editor quill em uma página html, sem fazer a instalação com npm, mas usando as api´s via internet com http, no entanto não consigo fazer a tecla enter funcionar para mudança de linha, tentei essa configuração abaixo, mas não funcionou.
       
      modules: {       syntax: true,       toolbar: '#toolbar-container',       keyboard: {         bindings: {           enter: {             key: 13,             handler: function(range, context) {                       quill.formatLine(range.index, range.length, { 'align': '' });             }           }  
       
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.