Search the Community
Showing results for tags 'Camera'.
-
What I'm trying to accomplish is to basically write all my game logic in world units and use camera to see part of it rendered on the screen. Let's say my world is an infinite plane and I want to add a sprite, which will have dimensions of one unit in x axis and one unit in y axis. Then, I define a camera with dimensions of 4 units on x axis and 2 units on y axis. Visualization below. To get close to my desired result I followed the example in this blog post and used RenderTextureSystem to actually define source canvas dimensions equal to my world dimensions and target dimensions to the browser window size. Here is the code class WorldContainer extends DisplayObject { sortDirty: boolean; public content: Container; public camWidth = 4; public camHeight = 2; public camOffsetX = 0; public camOffsetY = 0; constructor() { super(); this.content = new Container(); } calculateBounds(): void { return this.content._calculateCachedBounds(); } removeChild(child: DisplayObject): void { this.content.removeChild(child); } removeChildren(): DisplayObject[] { return this.content.removeChildren(); } addChild(child: DisplayObject): DisplayObject { return this.content.addChild(child); } render(renderer: Renderer) { const targetWidth = renderer.view.width; const targetHeight = renderer.view.height; const targetRatio = targetWidth / targetHeight; const sourceWidth = this.camWidth; const sourceHeight = this.camHeight; const sourceRatio = sourceWidth / sourceHeight; let requiredWidth = 0; let requiredHeight = 0; if (sourceRatio >= targetRatio) { // source is wider than target in proportion requiredWidth = targetWidth; requiredHeight = requiredWidth / sourceRatio; } else { // source is higher than target in proportion requiredHeight = targetHeight; requiredWidth = requiredHeight * sourceRatio; } renderer.renderTexture.bind( null, new Rectangle(this.camOffsetX - this.camWidth / 2, -this.camOffsetY + this.camHeight / 2, this.camWidth, this.camHeight), new Rectangle((targetWidth - requiredWidth) / 2, (targetHeight - requiredHeight) / 2, requiredWidth, requiredHeight), ); this.content.render(renderer); renderer.batch.flush(); renderer.renderTexture.bind(null); } updateTransform() { super.updateTransform(); const { _tempDisplayObjectParent: tempDisplayObjectParent } = this.content; this.content.parent = tempDisplayObjectParent as Container; this.content.updateTransform(); this.content.parent = null; } } I have done some extra work to preserve aspect ratio of camera, when drawing to canvas, so it won't get stretched and will just fit the screen. However, real issue comes when I try to make sprites, because when I give it a texture and let's say dimensions of my texture are 64x64 pixels, then my sprite is huge filling the whole screen. That's when I thought just setting width and height of the sprite should be enough. For example to recreate the example in the picture above, I would make the sprite like this and add it to the content of world container. const sprite: Sprite = Sprite.from('sadge.png'); sprite.anchor.set(0.5); sprite.x = 1.5; sprite.y = 1.5; sprite.width = 1; sprite.height = 1; worldContainer.content.addChild(sprite); Now, what I don't like about this solution is, that when I add child sprite to that previous sprite and give it's x to be equal to 1, y to be equal to 0, I expect it to appear on second row and third column. However, not only the child sprite is not in my expected position, it's also not visible. After, hours of debugging I found out, that when setting width and height for parent sprite, under the hood pixi modifies scale and it ruins everything for child sprite. If, I set sprite's width height to be 1x1, it sets scale for sprite to be ( 4 / canvas_w, 2 / canvas_h), which is very tiny and because that scale is also applied to its children, they get so small that they are not visible. I know that I can manually multiply by inverse of the scale ratio for every child and cancel that effect, but to be frank it is very ugly solution. I was wondering if you could help me to fix this issue, or give me a directing advice on how to approach it. If feels like I am solving this whole world unit issue in a very wrong way and there is far simpler and neater solution. I've been struggling with this thing for weeks now and would really appreciate any help.
-
Hi everyone, I'm trying to build a camera for a large exported JSON map. Currently, what I'm doing is pivoting the movement around the player to give the illusion of movement like this in the game loop ``` this.playerOffsetX -= this.sprite.vx; this.playerOffsetY -= this.sprite.vy; this.player.x += this.sprite.vx; //NOTE, this does not actually move the sprite, this.player is just a Javascript object with an x and y property this.player.y += this.sprite.vy; this.staticBackground.pivot.set(this.player.x, this.player.y); ``` Now after the player has moved a number of pixels = the length of my file, I re-draw the map by adjusting the row and column of the original map and re-draw everything again (inefficient, I know for now until I get it working correctly) ``` renderMap(initial = false) { //move the camera to give illusion of movement // if (newLeftX === this.leftX && newLeftY === this.leftY && !initial) return; const layers = this.map.layers; //camera spans 10 tiles to right and down const mapWidth = this.map.width; const mapHeight = this.map.height; var updateMap = initial; if (!initial) { // this.staticBackground.position.set(this.sprite.x, this.sprite.y); if (this.playerOffsetX !== 0) { if (this.playerOffsetX % SQUARELENGTH === 0) { this.staticBackground.removeChildren(); const step = Math.floor(this.playerOffsetX / SQUARELENGTH); this.leftX -= step; if (this.leftX <= 0) { this.leftX = 0; } this.playerOffsetX = this.sprite.width / 2; updateMap = true; } } if (this.playerOffsetY !== 0) { if (this.playerOffsetY % SQUARELENGTH === 0) { this.staticBackground.removeChildren(); //TODO: fix this const step = Math.floor(this.playerOffsetY / SQUARELENGTH); this.leftY -= step; console.log("step: ", step," new y:", this.leftY); if (this.leftY <= 0) { this.leftY = 0; } this.playerOffsetY = this.sprite.height / 2; updateMap = true; console.log("refresh y: ", this.leftY); } } if (!updateMap) { return ; } } else { this.staticBackground.position.set(0, 0); } console.log("ran: ", this.leftX, this.leftY); for (let layer = 0; layer < layers.length; layer++) { const currLayerData = layers[layer].data; //calculate exact window we need to iterate, since window is square //but data is a 1D array, we will still encounter some elements outside window //still a 4x improvement const start = (this.leftY * mapWidth - 1) + this.leftX; const end = start + WINDOW_WIDTH + (WINDOW_HEIGHT * mapWidth) + 1; console.log(this.leftX, this.leftY, start, end, currLayerData.length); for (let i = start; i < end; i++) { //position on our screen //data is stored as one very long string, representing a 2D grid //y and x are in terms of rows and cols of tiles not raw pixels const y = i / mapHeight| 0; const x = i % mapWidth | 0; //choose tile if (currLayerData[i] !== 0 && currLayerData[i] < 100) { //only continue if in window of map const yOffset = y - this.leftY; const xOffset = x - this.leftX //tile window is WINDOW_WIDTH x WINDOW_HEIGHT if (yOffset >= -5 && yOffset <= WINDOW_HEIGHT + 5 && xOffset >= -5 && xOffset <= WINDOW_WIDTH + 5) { //elements are stored corresponding to sequential ids, that map back //to the tileset - 20 = # of tiles in each row in our tileset const tileRow = Math.floor(currLayerData[i] / 20); const tileCol = ((currLayerData[i] - 1) % 20); const sprite = new PIXI.Texture(TextureCache["/static/img/rpg.png"]); sprite.frame = new PIXI.Rectangle(tileCol * SQUARELENGTH, tileRow * SQUARELENGTH, SQUARELENGTH, SQUARELENGTH); const layer = new PIXI.Sprite(sprite); layer.x = xOffset * SQUARELENGTH; layer.y = yOffset * SQUARELENGTH; this.staticBackground.addChild(layer); } } } } } ``` The problem is that I'm getting some weird tearing issues - I think the problem is to do with pivoting - I pivot the map around the player coordinates (which keeps increasing or decreasing) but when I redraw the map in the given area, the pivot is not adjusted for that offset, but I'm not sure which offset that is. Anybody have an idea of why this is not working correctly? Is there an easier/better approach?
-
Hi, I'm trying to replicate the camera movement from a typical FPS game. I want the camera to follow the player's mouse, without the need to click at all. Here's what I've got so far: var lastMove = 0;oldx = 0,oldy = 0,mousemovemethod = function (e) { if(Date.now() - lastMove > 40) { if (e.pageX < oldx) { camera.rotation.y -= .1; } else if (e.pageX > oldx) { camera.rotation.y += .1; } if (e.pageY < oldy) { camera.rotation.x -= .1; } else if (e.pageY > oldy) { camera.rotation.x += .1; } oldx = e.pageX; oldy = e.pageY; lastMove = Date.now(); }}document.addEventListener('mousemove', mousemovemethod);The camera movement is rough and intermittent. I'd like it to be smooth with a bit of easing. Here's a link to the full code: http://www.babylonjs-playground.com/#WM1VE My question: How can I smooth out the rotation code above, or is there a better way? Solution: camera.cameraRotation.ycamera.cameraRotation.x cameraRotation provides the smooth transition I was looking for.
-
In many strategy games it's common that the world is larger than what you see on the screen, and the user will "drag" themself around the level to move around the world. How can I implement this in Phaser? I've seen examples to drag sprites within a level, but not to drag basically the camera view itself. Something like this example: http://examples.phaser.io/_site/view_full.html?d=world&f=fixed+to+camera.js&t=fixed%20to%20camera but where you are moving by dragging with either the mouse or the touch instead of the arrow keys
-
I am making a level editor for my platformer game. I add images to screen on the mouse position when clicked. It was going well but when I added a camera which move with arrow keys when I try to add the sprite. It's not added where my mouse clicks and sometime it does not add. In the game I have a scrolling camera and I wan't to use it here also. when i press on the highligted place I can't add the platform. The screen is scrolled already. game.world.setBounds(0, 0, 2000, 600) background.fixedToCamera = true if (cursors.right.isDown){ game.camera.x +=30 } else if (cursors.left.isDown){ game.camera.x -= 30 } my code for camera
-
Hey all! I am both new to Babylon and these forums! I want to make a First Person Camera that moves in a direction based on its rotation (e.i. like a forward/backwards functionality with W/S). Only problem is I don't know how to do this without maybe physics engines enabled or making a bunch of really janky movements. I want something like Unity's Transform.forward. How do I achieve this?
-
Hello, I'm new here, so firstly I want to greet with all of you. Regarding my question, or maybe problem - some background here: I want to create minimal for My 2D space shooter. I check tutorials on labs.phaser where I saw example with creating MiniMap with second camera - it sounds good. So I created class for My MiniMap: import Phaser from 'phaser' export default class MiniMap extends Phaser.Cameras.Scene2D.Camera { constructor ({ scene, x = 10, y = 10, width = 192, height = 192, zoom = 0.1, scroll = { x: 960, y: 960 } }) { super(x, y, width, height) this.scene = scene this.zoom = zoom this.scroll = scroll } init () { this.scene.cameras.cameras.push(this) this.scene.cameras.addExisting(this) this.setZoom(this.zoom) this.setScroll(this.scroll.x, this.scroll.y) return this } } And I'm creating it in My GameScene in create() function: create () { this.bgImage = new BackgroundImage({ scene: this }).init() this.miniMap = new MiniMap({ scene: this }).init() this.miniMap.setBackgroundColor('black') this.player = new Spaceship({ scene: this, x: 0, y: 0 }).init() this.camera.startFollow(this.player) } About My sizing, BackgroundImage and Bounds are 1920 x 1920 px, so in MiniMap we had 192 x 192 and also zoom as 0.1 (1/10 of real game world). It should create Map with the whole world, but it is cut on left and top and have free space at right and bottom (attachment). How to fix it? Also, maybe you can give me some tips how to change Spaceship sprite on MiniMap (second camera) as for example dot? Thanks for advance! Best, DaaV
-
Hi there, I'm currently building a FPS game with babylon.js (love the engine <3) and sometimes the player has a sniper rifle, and when they scope I would like to: 1. Have the UniversalCamera zoom in. 2. Decrease the UniversalCamera's angularSensibility (pan around slower). 3. Overlay a recticle image. Right now I know how to do 2 & 3 but not 1. I've looked around, searching for a way for the camera to zoom in but without luck. I'm wondering if BJS has a function for this, or if not, is there some other way I can achive this? If any of you guys know how I can achive this please let me know, thanks. PS. I haven't posted any code since I think this is a general question, let me know if you want the code though.
-
Hey I am trying to build a round minimap. I do not want to duplication rendering of all game objects, so I decided to add a second Camera. My Issue: Is there any way to get the Camera Object in a round shape? The game is an endless generated Map getting chunk data from a nodejs server. So the minimap should stay quite flexible. A camera fits my needs but the shape issue still exists. I would appreciate help a lot
-
Hi, I'm basically making a doodle jump based game, but since I'm really new to Phaser and barely find any examples on how to handle a custom camera, I'm asking for help on this forum. I want the camera to follow the player when it goes up, but stop following the player as it goes down. I've looked at a lot of Phaser 2 examples but these confuse me only more. This is my code for the camera, right now it basically follows the player up and down. (the clouds are removed below the camera view, so the player keeps falling when it misses a cloud) cameraMovement() { this.cameras.main.setBounds(0, - this.player.yChange, 500, 800); this.cameras.main.startFollow(this.player); }
-
I'm using the Babylon toolkit for Unity and I'm trying to use the script 'CameraRig.cs'. I've attached the script at the main camera, but nothing happen. Can someone help me to figure out how to add an orbit camera ? I'm developing a 3d viewer so the camera should only orbit around the object. I know how to do it babylonjs alone, but I don't understand how I can use the script in the toolkit. thanks
-
Good day, Sir. First, I want to say Thanks to everyone, who spent time to read this, I will be glad and happy to hear any advices or notes about this issue. Here is a PG: https://www.babylonjs-playground.com/#AI1MQC#2 Please, hide the SetEnviroment(), getPointsArray() and cameraMoveAnimation() functions bodies to make code more readable, I specially out them from main code. As you can see, there is 2 important lines: 82 and 83. Each points from "points" array is a real data from real project, that is not random numbers. So, the camera should move from: point1 to point2, then point2 to point3, then point3 to point4, and so on. There is no problems in start points, it's moving smoothly, but at point7 to point8 (and some others) camera rotates around itself. (Playground setted by default to reproduce this). It look like... flipping possible. I am using pivot method to create camera, and I can not use ArcRotateCamera in real project, because in some points it's broken because of gimbal look, for example, at point8 as I remember, it will dispose, and then appear, ArcRotateCamera was first, what I tried. So, the question is: how to prevent camera flipping around itself? ===================== upd: I tested a little more, if I am using lookAt method without animation and just setting new quaternion, it reproduces the same problem, but I don't have any idea why it happens and why it's changing rotation angle. ======================= upd2: I made additional example, which shows problem from outside: https://www.babylonjs-playground.com/#X66D1S#1 As you can see, big red sphere doing strange movement but if you change animation arguments in lines 82 and 83 from points[7], points[8] to points[6], points[7], sphere will do exactly what I needed, so what is it? Why it happens? How can I prevent this?
- 8 replies
-
- animations
- mathematic
-
(and 4 more)
Tagged with:
-
solved ArcRotate Camera Custom Input to move LockedTarget
jps0611 posted a topic in Questions & Answers
Howdy friends, Got an issue I'm trying to sort out with how I want to customize the input controls for the ArcRotate Camera. I'd like to take the existing ArcRotate Camera and keep the Alpha inputs standard, but update the Beta inputs to move the lockedTarget of the camera. So imagine "scrolling" the canvas would move the camera and instead of move the Beta of the camera. Unclear where to begin on this. @Deltakosh I'd setup a playground but given it wouldn't be much more than the default ArcRotate template I've not done that here. Thanks for any help/suggestions! JPS -
solved How target the camera to the real world orientation ?
cstfan posted a topic in Questions & Answers
Hi, I would like when I start the device orientation camera that the orientation is as a real world? For example, if I create 4 cubes around me with north, east, west and south, I want to see the north cube when my smartphone is facing north. Thank you very much in advance for your help. Stephan -
Not sure if it's a bug but it seems like camera property idleRotationWaitTime is not working. Look at this playground, whatever the time you put, it always wait 2-3 seconds before starting moving again : https://www.babylonjs-playground.com/#6FBD14#75
-
I am using the "camera.main.shake()" function How to do make sure that certain graphics like the UI ignore the shake? For example if had this box var newGraphic = this.add.graphics({ lineStyle: { width: 2, color: 0x555555 }, fillStyle: { color: 0xeeeeee } }); var rect = new Phaser.Geom.Rectangle(); rect.width = 500; rect.height =500; rect.x = 0; rect.y = 0; newGraphic.strokeRectShape(rect); Thanks
-
Today I got a headache from how... why... phaser3 handles the camera.setZoom(); - First thing I learned: all bodies need to be recalculated after .setZoom. - in WebGL works as expected. - in Canvas, Tilemaps are huge, the zoom isn't on point and even by recalculating the bodies, collision is way off. This could be reproduced by using this code and setting WebGL / Canvas. The code behaves differently depending on which you choose, and neither of both has a valid result. Am I missing something? Game config: // Game config type: Phaser.WEBGL, width: WIDTH, height: HEIGHT, scene: Level, resolution: 1, pixelArt: true, antialias: false, hidePhaser: true, roundPixels: true, backgroundColor: '161C22', zoom: 1, physics: { default: 'arcade', arcade: { gravity: { x: 0, y: 250 }, debug: true } }, tilemaps and camera: // Tilemap method setMap() { // # Add Tilemap this.config.map = this.make.tilemap({ key: 'map', tileWidth: 8, tileHeight: 8 }) const tileset = this.config.map.addTilesetImage('tilemap'); // # Add Tilemap Layers this.config.layers.background = this.config.map.createDynamicLayer(0, tileset); this.config.layers.midground = this.config.map.createDynamicLayer(1, tileset) this.config.layers.ground = this.config.map.createDynamicLayer(2, tileset); this.config.layers.forground = this.config.map.createDynamicLayer(3, tileset); this.config.layers.water = this.config.map.createDynamicLayer(4, tileset); // # Configure Tilemap Layers // replace with array of actual bodies this.config.layers.ground.setCollisionBetween([]); this.config.map.objects[0].objects.forEach((obj)=>{this.setMapObject(obj)}); // # Configure z indexes this.config.layers.background.setDepth(0); this.config.layers.midground.setDepth(1); this.config.layers.ground.setDepth(2); this.config.layers.objects.setDepth(3); this.config.layers.enemies.setDepth(4); this.config.layers.player.setDepth(5); this.config.layers.effects.setDepth(6); this.config.layers.water.setDepth(7); this.config.layers.forground.setDepth(8); this.config.layers.overlays.setDepth(9); this.config.layers.ui.setDepth(10); this.setTransition(); } // # Configure main camera const m = this.config.map; this.physics.world.setBounds(0, 0, m.widthInPixels, m.heightInPixels, true, true, true, true); this.cameras.main.setBounds(0, 0, m.widthInPixels, m.heightInPixels); this.cameras.main.setZoom(8); this.cameras.main.setRoundPixels(true); this.cameras.main.useBounds = false; this.config.layers.ground.setCollisionBetween(0, 8000); // add sprites this.config.player = new Player({ scene: this, x: 20, y: 30}); this.cameras.main.startFollow(this.config.player); this.physics.add.collider(this.config.player, this.config.layers.ground); Any thoughts, on this, would be helpful.
-
This is the order in which the cameras (relevant to me) extend each other, but also often override each other: UniversalCamera extends TouchCamera extends FreeCamera extends TargetCamera [extends Camera.] How come FreeCamera doesn't use rotationQauternion and allow rotation around its Z (roll) axis by default? After all, TargetCamera does use quaternions, even though it ignores the Z axis by design. But a FreeCamera should be that much free, right? Wrong? I saw that FreeCamera abstracts its inputs. It would make sense for the mouse input to use quaternions for full freedom of rotation in all axis. Desu ne? I'm itching to make a pull request that, while keeping backwards compatibility, adds more freedom to rotation (Z axis roll) and movement (QE for In/Out.) But I'm new, so I don't want to code stuff and then get denied. Visualization aid:
-
Need some help. I try to find what I am missing hear for days. But I don't get it.. Maybe someone of you can point me in the right direction. A moving sprite, that is followed by the camera, disappears on "certain" areas. For example in one scene: it disappears in the upper left and most left areas of the scene. In some others on all areas around the borders of the world. - Tilemaps and every other object are still visible. 1. The moving sprite does not involve any alpha 0 / 1 settings 2. The moving sprite does not die/destroy 3. The moving sprite does not set any kind of BlendMode 4. The moving sprite does not set any visibility 5. There are NO overlays that could cover up the moving sprite 6. Worldbounds and main cameras bounds are set (code below) this.physics.world.setBounds(0, 0, this.map.widthInPixels * SCALE, this.map.heightInPixels * SCALE, true, true, true, true); this.cameras.main.setBounds(0, 0, this.map.widthInPixels * SCALE, this.map.heightInPixels * SCALE); I also tested adding a second camera, it is the same behavior, but here I can see, any time the moving sprite disappears, the camera background is set to a different color... and I don't know why this is happening. The game's code is too much to post it all. But basically, the only thing with bounds that is set, are the two lines, I posted here. At this time it is quite confusing and I already spend days investigating in it. I got no clue, why this is happening. Any hint is highly appreciated! cheers
- 1 reply
-
- visibility
- worldbounds
-
(and 2 more)
Tagged with:
-
phaser3 Camera: Contradiction in Doc for remove() and destroy()?
jamespierce posted a topic in Phaser 3
I apologize in advance if this should be obvious... Regarding destroying / removing cameras that I don't need anymore, I came across these two descriptions in the documentation that sound a bit contradicting to me: Camera.destroy(): CameraManager.remove(camera): So for destroy() it says that I should use CameraManager.remove(). However for remove() it says that I need to call Camera.destroy() to clear all references. @rich What's the "clean" way to do it? Call remove() first and then destroy() after? Or just one of the two?- 2 replies
-
- doc
- documentation
-
(and 2 more)
Tagged with:
-
Hi, It seems something is not finishing in the camera's fadeIn effect. If I use this code: var camera = scene.cameras.main; scene.time.delayedCall(5000, function() { camera.fadeOut(250); }, [], scene); camera.on('camerafadeoutcomplete', function() { camera.fadeIn(250); }); ... after the end camera stays a little dark, like not fully transparent. I've compared 2 screenshots. At the moment I'm forced to call camera.resetFX() to make colors brighter again. Can this be fixed?
-
I'm working on a camera that behaves as if tracking a spaceship. The Z axis rotation shouldn't affect looking up/down and right/left, as if I'm the pilot in the cockpit of the ship in space, up is always my local up. I tried the FollowCamera, but it only lets me rotate the target mesh so the camera yaws, but doesn't roll or pitch. I tried the Free/Universal cameras, but rotating the camera to roll skews the yaw and pitch, as if they're in global dimensions - instead of local. I couldn't find a local/global rotation option, or figure out using quaternions/matrices with it, no matter how much I read about those and tweaked the code. I know I could make this spaceship camera from scratch, using an empty/mesh as a pivot, but I don't want to miss on using the quality code that comes with the engine already. Any suggestions?