Jump to content

Search the Community

Showing results for tags 'js'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • HTML5 Game Coding
    • News
    • Game Showcase
    • Facebook Instant Games
    • Web Gaming Standards
    • Coding and Game Design
    • Paid Promotion (Buy Banner)
  • Frameworks
    • Pixi.js
    • Phaser 3
    • Phaser 2
    • Babylon.js
    • Panda 2
    • melonJS
    • Haxe JS
    • Kiwi.js
  • General
    • General Talk
    • GameMonetize
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered
    • Marketplace (Sell Apps, Websites, Games)

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Twitter


Skype


Location


Interests

  1. Play It Now: https://cutedressup.com/game/princess-runway-fashion-look/ Welcome to the Princess Runway Fashion Look. Princesses Anna, Elsa, Moana, Ariel, Snow White, and Jasmine are eagerly waiting for an upcoming fashion event. They planned to show their fashion skill with their stunning look to attract everyone. Help the princess by browsing the wardrobe and picking a perfect outfit for each one of them.
  2. Hi! Maybe someone could help with a freeze of an animation while we loading/preloading textures. There are background and several big animations. After scene have started to change and transition animation have started, main container is cleared and new background with different big animations are added. This freeze is connected with scene rendering. Does somebody know the way to deal with this problem? ======================= Version pixijs 6.2.2 ======================= Application virtual_h = 2276; virtual_w = 1280; render = PIXI.autoDetectRenderer(virtual_w, virtual_h, { resolution: window.devicePixelRatio, autoResize: true, antialias: false, }); gameContainer.height = virtual_h; gameContainer.width = virtual_w; document.getElementById("game").appendChild(render.view); ======================= Animation let animationRaw = PIXI.Loader.shared.resources["animationRaw"].spritesheet.animations["animationRaw"]; let animation = new PIXI.AnimatedSprite(animationRaw); animation.autoUpdate = true; animation.loop = false; animation.onComplete = function() { animation.stop(); }; gameContainer.addChild(animation); ======================= Preload render.plugins.prepare.upload(gameContainer); ======================= Ticker ticker.add(function() { render.render(gameContainer); }); ======================= Switch a scene gameContainer.removeChildren(0, gameContainer.children.length); let animationRawNew = PIXI.Loader.shared.resources["animationRawNew"].spritesheet.animations["animationRawNew"]; let animationNew = new PIXI.AnimatedSprite(animationRawNew); animationNew.autoUpdate = true; animationNew.loop = false; animationNew.onComplete = function() { animationNew.stop(); }; gameContainer.addChild(animationNew); =======================
  3. Freckles

    Input in PIXI

    From what I've read I need PIXI text input plugin to use that feature. I need to write input text module as I don't want to use plugins. I'd be thankful if you help me out to understand if I can use HTML tags in Pixi.js somehow (Everything's build up on canvas, and I haven't seen any example this far that does so, maybe I'm missing sth) if not could you provide some resources that can help me figure it out? Are there any finished components I can use or do I need to write anything from scratch? (not only input related but also buttons and stuff like that) Thanks in advance!
  4. There is a problem in different browsers, for example, if a roulette ball in Chrome stops at a certain number in another browser, it stops at another. Can the difference between physics world.step (cannon.js) in different browsers?
  5. In HTML we are importing several javascript frameworks. Some of them needs any one server for running this like local or web server. Is there any possibilities or tricks to run that kind of html file without server. I am using three.js within a html file. Basically three.js requires server to run the file. I need to run that without any server.
  6. Hello, I'm a web programmer with 3 years of experience (currently a senior developer). I've always been a fan of videogames and now I'm starting learning game development just for fun. Like in any type of development , you always face problems and learn of those. Sharing is the strongest tool to learn, you help other people to prevent/fix mistakes and they help you. What am I looking for?: People like me that is learning to develop games and want to meet other people to make games with them, share experiences, ask&answer questions. How will we organize? I have experience managing large Telegram groups and also creating bots for groups. It is a good starting point since most of the people always carry the phone everywhere and also has a web/desktop application, also Telegram offers us a direct communication without compromising your privacy (you don't need to give real info or phone number to the rest of the group). If we start growing, we can just move to another platform you want (Discord, Slack, whatever is of your preference). Do you have any project scheduled? Yes, I want to build a fun roguelike, here is my current roadmap of the game: I am an artist, can I join? Sure! I'm sure you can learn from us and we can learn from you, Keep in mind that sound artists, level designers, programmers.. work together and they need to understand all the other positions to work properly. Of course this is a flexible diagram, I don't do this as my job and I don't have any deadlines, creating a roadmap just helps me with organization so I don't start wrongly (which with end even worse :P). Have in mind that my only goal is just learning, I'm not in a rush to make money or finding a job Just feel free to contact me if you want to join or if you doesn't like something of my post.
  7. this.cursor = new PIXI.Graphics(); /****some code ****/ this.addChild(this.cursor); setInterval(function () { this.cursor.alpha = 1; //alpha is undefined setTimeout(function () { this.cursor.alpha = 0; }, 500); }, 1000); /*************************************************************************************/ let a = this.cursor = new PIXI.Graphics(); /****some code ****/ this.addChild(this.cursor); setInterval(function () { a.alpha = 1; setTimeout(function () { a.alpha = 0; }, 500); }, 1000); Hey guys, could you please explain why I get ''alpha is undefined'' in the first case and it works alright in the second case? TBH I don't know if this question is pixi related or js related. Also this.realInput.setAttribute( `style`, `position: relative; opacity: 0`, `type`, `password`, ); this.realInput.setAttribute( `inputmode`, `${this.inputMode}` ) //////////////////////////////////////////////////////////////////////////////// this.realInput.setAttribute( `style`, `position: relative; opacity: 0`, `type`, `password`, `inputmode`, `${this.inputMode}` ); Why is the first case working and the second one doesn't, isn't that the same somehow?
  8. hi, i am intrested in purchesing mulltyplayer games for a venture i am developing. my general specifications are : 1. HTML 5 an js based games that can be deployed in a web view. 2. mobile frindly games. 3. acsess to the minified source code so we can change the game assets, images, audio and ect. 4 the cration of game rooms needs to be acsessed directly - witout a lobby - including the game id and parameters in the url ((i.e. "www.example.com/backgammon?room_id=test") 5. cration of the game rooms should be handled a call to an endpoint - for example : a. The user on our client clicks "New Game" for a specific game b. Our client sends a request such as "API_URL/backgammon/newgame" and receives the room ID c. Our client navigates to the game and joins it d. The user can share the room ID to friends so that the friends join the same room directly e. Once everyone leaves the room it can be terminated automatically if possible - i would like to scheduall a zoom/skype call to understand priceing, techincall issuse and see if we can find a way to work together. thank you, Itamar.
  9. import { UnderlineText } from './underlineText.js'; let Application = PIXI.Application, loader = PIXI.Loader.shared, resources = PIXI.loader.resources, Sprite = PIXI.Sprite, text = PIXI.Text; let app = new Application({ width: window.innerWidth, height: window.innerHeight, antialias: true, transparent: false, resolution: 1, autoDensity: true }); document.body.appendChild(app.view); let underLine = new UnderlineText(null, [100, 385], null, null); app.stage.addChild(underLine); //app.loader.onError.add((error) => console.error(error)); Above is my index.js file. I have the module called UnderLineText. It doesn't work properly as it shows underline but not the text itself. It does count the width of the text, thus displaying the line underneath but I don't know how to make the text visible. Any ideas what I did wrong? P.S. I'm using PIXI js and I'm a newbie. class UnderlineText extends PIXI.Graphics { constructor(text, points, textFontSize, textColor) { super(); let t = this.textFontSize = textFontSize || 12; let s = this.lineWidth = 1; let c = this.textColor = textColor || "0xFFFFFF"; let ut = this.text = text || "Ողջույն"; let textStyle = { fontFamily: 'Arian AMU', fill: c, fontSize: t } let newText = new PIXI.Text(ut, textStyle); this.points = points; points[0] = newText.position.x; points[1]= newText.position.y; this.lineStyle(s, c); this.moveTo(points[0], points[1] + 13); this.lineTo(points[0] + newText.width, points[1] + 13); } } export { UnderlineText };
  10. I am trying to make a game so I tried to load a tileset, to help me make the game, but when I try to play my game, this shows on the console- ```Cannot read property 'addTilesetImage' of undefined``` This is my code: ``` Ball.Level1 = function (game) {}; Ball.Level1.prototype = { create: function () { var map; var layer; this.map.addTilesetImage('element-h'); this.map.addTilesetImage('element-w'); this.map = this.game.add.tilemap('map', 32, 32); this.layer = this.map.createLayer(0); this.layer.resizeWorld(); } }; ``` this is what I pre-load! ``` this.load.image('element-w', 'img/element-w.png'); this.load.image('element-h', 'img/element-h.png'); this.load.tilemap('map', 'img/Teste.csv'); ``` Thank for your help!
  11. Few days back I released my first mobile game made using Phaser 3 framework. It's a simple game but was hell lot of work. In the end I learnt a lot in the process. https://lakshyadubey.itch.io/rgb
  12. I do everything by the example : this.pauseBtn.on('pointerdown', function (event) { timer = this.time.addEvent({ delay: 10000, callback: hidePopup, callbackScope: this}); }); When compiling it issues an error : Uncaught TypeError: Cannot read property 'addEvent' of undefined. How to fix it?
  13. Hi, I'm building a crowd simulation (using Aggregate Dynamics for Dense Crowd Simulation, if it meters) and as for now I have 100 moving agents and one target in the middle. What I'm trying to do is to create a heatmap so I can see and analyze which paths are the most common for them to use, any ideas how to do it with Babylon? I'm quite new to it, this is my first project using Babylon, maybe there are some build in tools for that purposes? Tried to google it but no success. Thanks for any kind of advice!
  14. Hi, I'm new with Phaser, I'm wondering how can I create a group of enemies that appears at the side of the screen in a random Y position between 550px and 745 px, after they appear they need to start to fire to my character Right now I have a function to create the bullets and how they will be fired: createBullets:function(laserToFire,track,offsetX, offsetY, bulletDirection,fireRate,bulletSpeed){ weapon = gameSP.add.weapon(10, laserToFire); weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; weapon.bulletSpeed = bulletSpeed; weapon.fireRate = fireRate; weapon.trackSprite(track, offsetX, offsetY); weapon.fireAngle = bulletDirection;right } So what I'm looking to do is to have each one of my enemies within the group to fire to my character. Thanks in advance.
  15. Well... I want to learn how to make games, for PC, browser or mobile. I started to learn logic then I passed to HTML and CSS, I learned the basics of those two then I started to see the basic of JS. I did a break for a few months to focus on school, but now I'll return my programming studies. And I heard that C# is the best choice for gamedev using the Unity Engine. So, I want to know what is the best choice, stay learning JS or start to learn C#?
  16. This is how far I got. I want the animation(dragon-attack) to complete when the player hits the dragon and then continue the 'dragon-fly' animation. What would be a solution? function preload() { this.load.spritesheet('dragon', 'assets/demon-idle.png', { frameWidth: 160, frameHeight: 144 }); this.load.spritesheet('dragon-attack', 'assets/demon-attack.png', { frameWidth: 240, frameHeight: 192 }); } function create() { dragon = this.physics.add.sprite(400, 300, 'dragon'); dragon.setBounce(0.4); dragon.setCollideWorldBounds(true); dragon.setDisplaySize(100, 100); this.anims.create({ key: 'dragon-attack', frames: this.anims.generateFrameNumbers('dragon-attack', { start: 0, end: 10 }), frameRate: 10, repeat: -1 }); this.anims.create({ key: 'dragon-fly', frames: this.anims.generateFrameNumbers('dragon', { start: 0, end: 5 }), frameRate: 10, repeat: -1 }); this.physics.add.collider(player, dragon, meetsDragon, null, this); } function meetsDragon(player, dragon) { playerHealth -= 10; dragon.anims.play('dragon-attack', true); } thanks for your help!
  17. Hey Folks, I hope you can help. I am fairly new to Phaser 3 and am currently working on a platformer where my character can run, jump and collect collectibles. My game is modularised through WebPack everything else is plain JS along with the Phaser 3 framework. I am using Tiled where I export my levels as json files and the initial level loads perfectly with all collision tiles in place and working as expected. I've hit a road block with loading/starting new levels. I'll try and explain with my code to clarify. I've reduce the code significantly to make it easier to read. main.js: Entry file // Main.js import 'phaser'; import { Cave } from 'scenes/cave'; import { Playground } from 'scenes/playground'; var config = {...}, scene: [Cave,Playground] }; var game = new Phaser.Game(config); Cave.js. For the sake of conciseness, I've placed the this.scene.start in the update function so the new scene initialisation happens immediately. MapSetup function is further down. // Cave.js import 'phaser'; import MapSetup from 'modules/map-setup.js'; import CollectibleSetup from 'modules/collectible-setup.js'; const mapSetup = new MapSetup(); const collectibleSetup = new CollectibleSetup(); export class Cave extends Phaser.Scene { constructor () {super('Cave')} preload() { this.load.tilemapTiledJSON('map', 'assets/levels/cave/cave.json');// map made with Tiled in JSON format this.load.spritesheet('cave', 'assets/levels/cave/cave.png', {frameWidth: 64, frameHeight: 64});// tiles in spritesheet } create() { // Setup up map for this scene/level var mapObj = mapSetup.sceneMap(this, 'map', 'cave', 'world') this.map = mapObj.map; this.physics.add.overlap(this.player, this.stars, collectibleSetup.collectStar, null, this); }// create update () { this.scene.start('Playground') } Playground.js // Playground.js export class Playground extends Phaser.Scene { constructor () {super('Playground')} preload() { this.load.tilemapTiledJSON('map', 'assets/levels/playground/map.json');// map made with Tiled in JSON format this.load.spritesheet('tiles', 'assets/levels/playground/tiles.png', {frameWidth: 70, frameHeight: 70});// tiles in spritesheet } create() { // Setup up map for this scene/level var mapObj = mapSetup.sceneMap(this, 'map', 'tiles', 'World') this.map = mapObj.map; this.physics.add.overlap(this.player, this.stars, collectibleSetup.collectStar, null, this); }// create } MapSetup.js. The issue occurs here when the PlayGround scene is initiated. import 'phaser'; export default class MapSetup { sceneMap (ctx, key, tileSetImage, dynamicLayer) { // Map var map = ctx.make.tilemap({key: key}); console.log('map',map) // tiles for the ground layer - tilesets.name` var groundTiles = map.addTilesetImage(tileSetImage); // create the ground layer - layers[i].name var groundLayer = map.createDynamicLayer(dynamicLayer, groundTiles, 0, 0); // the player will collide with this layer groundLayer.setCollisionByExclusion([-1]); // set the boundaries of our game world ctx.physics.world.bounds.width = groundLayer.width; ctx.physics.world.bounds.height = groundLayer.height; return {map:map, groundTiles:groundTiles, groundLayer:groundLayer} } } I'll try and explain the issue as I understand it. When Playground is initiated, the following error fires in the console and it's because the the groundTiles & groundLayer variables return null so the setCollisionByExclusion doesn't work. When I console.log the map variable that get's assigned in the sceneMap function it returns: The tileset name is still referencing the cave json object and not the playground one. I don't understand why that is. My understanding is that a scene is automatically stopped when a new scene is started and that each scene is it's own class so i'm a bit baffled as to why previous references are still in place. What am I missing? Any help would be much appreciated. Thanks, All Moe
  18. I am currently using the Phaser project template located on Github. I tried to search online for a way to minify my game files, yet I've ran into pages that talk about using 'GruntJS'. I am currently not familiar with the javascript task runner. Can anyone give me links to tutorials on how to minify phaser games? Or can anyone post a detailed description on how to do so? I would appreciate it greatly.
  19. Hello! I'm find the perfect animation example but it works only on one image and in default mode (autoplay on page load). I need to init this only on mouseenter event and for each current image. This is example in codepen I'm found contidion to mouseenter and mouseleave event if ( options.interactionEvent === 'hover' || options.interactionEvent === 'both' ) { slidesContainer.pointerover = function( mouseData ){ mouseX = mouseData.data.global.x; mouseY = mouseData.data.global.y; TweenMax.to( displacementFilter.scale, 6, { x: "+=" + Math.sin( mouseX ) * 100 + "", y: "+=" + Math.cos( mouseY ) * 100 + "" }); rotateSpite(); }; slidesContainer.pointerout = function( mouseData ){ TweenMax.to( displacementFilter.scale, 1, { x: 0, y: 0 }); cancelAnimationFrame( rafID ); }; } The default animation settings is: if ( options.autoPlay === true ) { var ticker = new PIXI.ticker.Ticker(); ticker.autoStart = options.autoPlay; ticker.add(function( delta ) { displacementSprite.x += options.autoPlaySpeed[0] * delta; displacementSprite.y += options.autoPlaySpeed[1]; renderer.render( stage ); }); } I thought I can do something like this if ( options.interactionEvent === 'hover' || options.interactionEvent === 'both' ) { var ticker = new PIXI.ticker.Ticker(); ticker.autoStart = options.autoPlay; ticker.add(function( delta ) { displacementSprite.x += options.autoPlaySpeed[0] * delta; displacementSprite.y += options.autoPlaySpeed[1]; renderer.render( stage ); }); } This is pen with that "changed" part https://codepen.io/Frunky/pen/oMZbvr Also I need to load all items, but loads only one item. Why? Thanks
  20. Hi, I'm so happy to introduce you BIOK! BRIEF DESCRIPTION BIOK is pure strategy and intuition. A board game for the ingenious and the acute minds. Lead the creatures on the playing field to capture monsters and all kinds of items. Watch the monsters’ eyes and guide them to their preys. KEY FEATURES - Simple controls and fluid mechanics, super simple to understand and fun to use - 60 levels in many worlds with various maps - 10 creatures with different characteristics and abilities - Bonus and survival mode to solve puzzles and challenges - Special objects and environmental elements - Secondary missions and hidden objectives iOS - AVAILABLE Get BIOK from the Apple App Store ANDROID/WINDOWS - BETA You can access the beta: BETA ACCESS (remember to use your google account) MORE ABOUT BIOK You can read more about on the official BIOK game page. FOLLOW US Send us any commend and advice. Help us to make a better game. Facebook | Twitter | Web
  21. Hi! I'm an experienced programmer with C++, but just getting started with JavaScript. I'm making a simple 2D game to get started. I'm using the CreateJS library to do my image/spritesheet manipulation. Right now, I'm trying to create a Sprite class, which will set up a spritesheet in the constructor, and draw the sprite with coordinates in the draw() function. (a member of my Sprite class) Anyways, I'm doing some debugging now. My program stops in the constructor of my Sprite class, and I can't figure out why. To anyone with CreateJS experience, what is wrong with my constructor function?!?!?! Thanks! class Sprite { constructor(src, frameWidth, frameHeight) { window.alert("DEBUG constructor. " + src + ", " + frameWidth + ", " + frameHeight); //Gets here this.spriteSheet = new createjs.SpriteSheet({ images: [queue.getResult(src)], frames: {width: frameWidth, height: frameHeight}, animations: { ani: [0,4] } }); window.alert("DEBUG end constructor"); //Never gets here } draw(x, y) { animation = new createjs.Sprite(this.spriteSheet, "ani"); animation.regX = 99; animation.regY = 58; animation.x = enemyXPos; animation.y = enemyYPos; animation.gotoAndPlay("ani"); stage.addChildAt(animation,1); } }
  22. Hello guys, how can I control the download event with a gamepad? I just want an action while pressing the button. To do the same action, I'm going to press the button again. I need this action, but with a gamepadd button. Tahnk you all (Phaser.Input.Keyboard.JustDown(cursors.up) //the gamepad pad = this.input.gamepad.getPad(0);
  23. I was trying with Phaser where i saw that this gets some kind of blurred when moving (ingame) Testet it in Canvas & WebGL both had the same result then i tried it to setting `pixelArt` to false in the gameconfig and when i tried it then, it worked smooth, but it seemd that it had activated some kind of antialiasing so it got washed-out but the moving was smooth Phaser 3.8 (Original) Tileset tiles 16x16 (no spaceing / margin) (Extruded) Tileset tiles 16x15 (1px margin / 2px spaceing) Map made with Tiled Vivaldi & Chrome & Windows Edge Tileset Extruder: https://github.com/sporadic-labs/tile-extruder Code Example / Project: https://github.com/hasezoey/phaser-tiled-test Original Question: https://github.com/photonstorm/phaser/issues/3685 (moved to here)
  24. Hello, I wanted to extend the class BABYLON.Mesh with some functions, but I have problems. I created a file that does the following (extend.js): import BABYLON from 'babylonjs' import Helper from './helper.js' const {roundFloat} = Helper class Mesh extends BABYLON.Mesh { constructor () { super() console.log('check') } getMeshBounding (axis, val) { const boundingInfo = this.getBoundingInfo() // Native Bounding Info const max = boundingInfo.boundingBox.maximumWorld const min = boundingInfo.boundingBox.minimumWorld if (axis) { const value = val === 'max' ? max : min return roundFloat(value[axis]) } else { return { max: {x: roundFloat(max.x), y: roundFloat(max.y), z: roundFloat(max.z)}, min: {x: roundFloat(min.x), y: roundFloat(min.y), z: roundFloat(min.z)} } } } } export default Mesh And in the file, I want to use it (loader.js / same directory): import Mesh from './extend.js' const Loader = { loadObject: (scene, pos) => { // Create a built-in "sphere" shape; its constructor takes 6 params: name, segment, diameter, scene, updatable, sideOrientation var sphere = Mesh.CreateSphere('sphere1', 16, 2, scene, false, Mesh.FRONTSIDE) .... } } export default Loader But apparently he doesn't do it, otherwise a console.log would come. I'm relatively new to the ES2015 and Vue. Don't be too hard.
  25. I've been working on an action RPG for quite a while now, and I finally got my map to appear. Now I'm having a hard time getting my character sprite to appear. I have no idea what I should do about this. Here's my code: //establish variables var canvasBg = document.getElementById("canvasBg"), ctxBg = canvasBg.getContext("2d"), canvasEntities = document.getElementById("canvasEntities"), ctxEntities = canvasEntities.getContext("2d"), canvasWidth = canvasBg.width, canvasHeight = canvasBg.height, player1 = new Player(), isPlaying = false, obstacles = [], //animation requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }, imgSprite = new Image(); imgSprite.src = "img/testroomImage.png"; imgSprite.addEventListener("load", init, false); player1.src = "img/player.png"; function init() { document.addEventListener("keydown", function(e) {checkKey(e, true);}, false); document.addEventListener("keyup", function(e) {checkKey(e, false);}, false); defineObstacles(); begin(); } function begin() { ctxBg.drawImage(imgSprite, 0, 0, canvasWidth, canvasHeight, 0, 0, canvasWidth, canvasHeight); isPlaying = true; requestAnimFrame(loop); } function update() { clearCtx(ctxEntities); player1.update(); } function draw() { player1.draw(); } function loop() { if (isPlaying) { update(); draw(); requestAnimFrame(loop); } } function clearCtx(ctx) { ctx.clearRect(0, 0, canvasWidth, canvasHeight); } function randomRange(min, max) { return Math.floor(Math.random() * (max + 1 - min)) + min; } function Player() { this.srcX = 0; this.srcY = 600; this.width = 35; this.height = 54; this.drawX = 400; this.drawY = 300; this.centerX = this.drawX + (this.width / 2); this.centerY = this.drawY + (this.height / 2); this.speed = 2; this.isUpKey = false; this.isRightKey = false; this.isDownKey = false; this.isLeftKey = false; } Player.prototype.update = function () { this.centerX = this.drawX + (this.width / 2); this.centerY = this.drawY + (this.height / 2); this.checkDirection(); }; Player.prototype.draw = function () { ctxEntities.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height); }; Player.prototype.checkDirection = function () { var newDrawX = this.drawX, newDrawY = this.drawY, obstacleCollision = false; if (this.isUpKey) { newDrawY -= this.speed; this.srcX = 35; //Facing North } else if (this.isDownKey) { newDrawY += this.speed; this.srcX = 0; //Facing South } else if (this.isRightKey) { newDrawX += this.speed; this.srcX = 105; //Facing East } else if (this.isLeftKey) { newDrawX -= this.speed; this.srcX = 70; //Facing West } obstacleCollision = this.checkObstacleCollide(newDrawX, newDrawY); if (!obstacleCollision && !outOfBounds(this, newDrawX, newDrawY)) { this.drawX = newDrawX; this.drawY = newDrawY; } }; Player.prototype.checkObstacleCollide = function (newDrawX, newDrawY) { var obstacleCounter = 0, newCenterX = newDrawX + (this.width / 2), newCenterY = newDrawY + (this.height / 2); for (var i = 0; i < obstacles.length; i++) { if (obstacles[i].leftX < newCenterX && newCenterX < obstacles[i].rightX && obstacles[i].topY -20 < newCenterY && newCenterY < obstacles[i].bottomY - 20) { obstacleCounter = 0; } else { obstacleCounter++; } } if (obstacleCounter === obstacles.length) { return false; } else { return true; } }; function Obstacle(x, y, w, h) { this.drawX = x; this.drawY = y; this.width = w; this.height = h; this.leftX = this.drawX; this.rightX = this.drawX + this.width; this.topY = this.drawY; this.bottomY = this.drawY + this.height; } function defineObstacles() { var treeWidth = 65, treeHeight = 90, rockDimensions = 30, bushHeight = 28; obstacles = [new Obstacle(78, 360, treeWidth, treeHeight), new Obstacle(390, 395, treeWidth, treeHeight), new Obstacle(415, 102, treeWidth, treeHeight), new Obstacle(619, 185, treeWidth, treeHeight), new Obstacle(97, 63, rockDimensions, rockDimensions), new Obstacle(296, 379, rockDimensions, rockDimensions), new Obstacle(285, 25, 150, bushHeight), new Obstacle(570, 138, 150, bushHeight), new Obstacle(605, 492, 90, bushHeight)]; } function checkKey(e, value) { var keyID = e.keyCode || e.which; if (keyID === 38) { //up arrow player1.isUpKey = value; e.preventDefault(); } if (keyID === 39) { //right arrow player1.isRightKey = value; e.preventDefault(); } if (keyID === 40) { //down arrow player1.isDownKey = value; e.preventDefault(); } if (keyID === 37) { //left arrow player1.isLeftKey = value; e.preventDefault(); } if (keyID === 32) { //spacebar player1.isSpacebar = value; e.preventDefault(); } }; function outOfBounds(a, x, y) { var newBottomY = y + a.height, newTopY = y, newRightX = x + a.width, newLeftX = x, treeLineTop = 5, treeLineBottom = 570, treeLineRight = 750, treeLineLeft = 65; return newBottomY > treeLineBottom || newTopY < treeLineTop || newRightX > treeLineRight || newLeftX < treeLineLeft; } Any ideas for what can be done to make the sprite appear?
×
×
  • Create New...