#monogame-and-libgdx-dev
1 messages · Page 1 of 1 (latest)
monogame
🤝
<@&133522354419662848> ^
!karma @rain compass
!karma @rain compass
name something you love and hate about monogame, for me I love how I could just start coding my game without having to learn any new tools, but I hate how hard it is to find tutorials on how to make custom shaders
monoagme shaders are the same as regular directx shaders
also, you will find a bunch of old xna shader samples on the internet
who?
I use an ecs framework called LeoECS to replace Monogame.Extended.Entities. It provides better performance, entity pooling via a world OM and respects the CPU cache.
Also, I use a GLSL framework/pipeline called GLSLOptimizerSharp, which is very nice to have in your content pipeline for cross platform shader support. Provides a wrapper for shader compiler for content pipeline to use glsl shaders instead of having to go for hlsl or the fx ones.
Respects the cpu cache eh
Sounds like it should perform like unity's ecs (the pattern isn't the speed boost its the cpu cache stack abuse)
Will check it out
Hello, recently I've been learning Monogame, and gamedev in general, and I've been wondering if design patterns are actually used in gamedev, I've seen that many people ignore them and go straight to development, and in case they are useful, which one would you recommend?
Yup, LeoECS is high in the charts for the independent ECS libraries in the way of performance thanks to CPU stack abuse. Its documentation is in Russian. Thankfully, a couple of forks have the docs translated to English pretty good. Here's the main repo: https://github.com/Leopotam/ecs - Sticking it through google translate does the trick.
It needs a little love to chop shop the third party plugins together and remove the compiler flags / debug code in the ifdef blocks, but the edits are simple and its real real fast. Only took about 24 hours to fix it up the last time he updated.
saber7ooth thanked popcron
I probalby should fork it and commit my local code, now that I mention it, because I use it often and have maintained my own through three of his revisions, I will when I am more awake.
I'll mess with a little jekyll installation and get it some docs before I share it here.
design patterns are tools. you use them when you need them
also see https://gameprogrammingpatterns.com/
Hello, I've started a youtube channel for 2D indie developers, C# tutorials (MonoGame) - take a look, leave feedback, thanks 🙂 https://www.youtube.com/c/GameDevQuickie/videos
https://github.com/loopyd/ecs-saber
As promised I return with at least some functional repo, docs are incomplete but I am working through the mass amount of functions locally so soon™️ I will eventually include a monogame sample project so that its use can be demonstrated when I finish documenting everything.
Got the DocsFX site working with GitHub actions so you can now browse library API documentation. I am still working on C1 end of pipeline to release project, I am following github codeQL security recomendations before I hook that up to deploy to releases, though. CodeQL is hooked up to validate PRs, I will put it into releases after I have finished removing security vulnerability from project as some warnings appeared, so please keep it in mind on Security tab. I gutted his whole framework out and basically have refactored all of it to make it engine agnostic and improved performance further by including LINQ and more modern .NET optimizations. My library is 17% faster than his thanks to just unrolling a lot of the loops and untanging a lot of spaghetti in the original. I spent about the last week on automating builds and docs so there will be much more of that fixing up and optimizing / as well as a full testing framework soon.
hello libgdx folks 👋🏻
yeah all 3 of you
So I have a weird problem in LibGDX where sometimes if I stay in a specific x position with my player, some tiles have a gap between them.
probably happens with y position as well
(the black tiles are indeed tiles)
sus
@stuck elk
<@&133522354419662848>
<@&133522354419662848> ^
you have wrong blendstate
I'm making a 3d game with c# monogame and I have a question regarding smooth alpha ribbon trails with forward rendering.
I organize my particles furthest to closest for when I draw them, which works fine for smooth alpha particles but how would you get ribbon trails to have smooth alpha since the ribbon trail is normally long and flat and go through the particles so its hard to tell if its before or after a particle. plus I currently draw 1 whole ribbon trail, I don't draw the ribbon trail in segments. Anyone have any ideas on how others do this?
Currently to fix the problem I dont use ribbon trails with alpha. But would like to use smooth alpha with ribbon trails.
got some pics?
also sounds like maybe you want a depth buffer?
how would you depth buffer a ribbon trail though since its long and curves in on itself sometimes
a depth buffer just tells the rasterizer to not draw if that pixel has a closer depth
i guess thats how defered rendering would handle alpha collision with particles and ribbon trails?
so even defered has to still order particles from furthest to closest?
idk the details
i just know its why games that use deferred have to render the transparency with dithering
ill find a screenshot that uses particles and ribbon trail
i dont think it lets me post pictures here
here is 2 screenshots that use ribbon trails and particles. the particles are organized from furthest to closest so they work perfectly fine. But the ribbon trail is just drawn after all the particles so the ribbon trail cannot use alpha at all
depth buffer i think should work
otherwise u get ugly 0 alpha around the ribbon trail which hides the particles like the pixel shader is forgetting particles are already drawn
i guess you draw the effects based on thier distance so you have a depth buffer for ribbon trail and a depth buffer for particles? and you merge the colour buffer with the 2 depth buffers?
no
read up on depth buffers
well if you mean for alpha
maybe(?)
but not two depth buffers
i know depth buffers are used in defered rendering to tell how far the colour, normal renders are
kinda same thing we doing for this?
a depth buffer tells you only what the z value was the last time that pixel was rasterized to
so if a second draw call produces a z value with greater than the existing, it's not drawn
also called a zbuffer
maybe you're thinking of a gbuffer?
anyway i gtg
@fleet palm here's a demo of the new version of the engine with that sandbox "floatbox" testing scene (used screen-to-gif to capture which caused some mouse artifacts and the yellow 'click' circle)
Hey! that's really awesome!
Hey CobaltHex, sorry I moved the post to #show-off-your-work
why does this not rotate correctly
Hi guys. Someone mentioned this channel for scripts, snippets, extensions, etc. I’m looking for JavaScript cause I’m developing a web game with p5 library. I’m asking cause, in case it doesn’t exist, I want to create some snippets for everyone.
the font there is really small and can you describe the issue you're seeing?
this channel is mainly for q&a, it is not to advertise
What makes you think I was advertising? I'm asking about scripts, snippets and extensions to develop web games with JavaScript and if no one knows of any I will create and share them for anyone to use.
You're advertising your services ( I don't mean selling) anyway this is for monigame and libgdx not webdev, that's #web-dev
i’m currently working on a 2d engine and i tried box2d for physics but it’s way too complicated for platofrmers, any suggestions?
use separating axis theorem
I've seen a lot about collision detection methods and stuff, how to make it better for rotated shapes or make it efficient with spatial hashing etc.
but no one really talks about combining the collision resolution with detection. resolution is the hard part imo lol
yes
i recommend a book on collision detection/resolution
got a good one specifically?
https://www.amazon.com/Real-Time-Collision-Detection-Interactive-Technology/dp/1558607323 is a good book, not sure how much it handles resolution
https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/swept-aabb-collision-detection-and-response-r3084/ is another placce to get started (particularly "swept collision resolution")
forgot to reply to this, thanks for the links!
yo thanks to this channel i might go back to libgdx
Hey, guys, did anyone manage to get omnisharp to work with MonoGame? I have a cleanly installed Windows and can't get it to work. Any tips?
I'm using VSCode*
Can anyone help me figure out HLSL hardware instancing with monogame?
SV_InstanceId ?
shouldn't be any diff than other dx implementations
I don't use the voice chat sorry
ah ok
so far, I think my normals may be screwed up. got nothing but black when trying to draw
can you open it in render doc/PIX?
nope
why not?
renderdoc complains
mostly. If i remove a specific variable from the lighting calculation in my shader, I can see it
looks perfectly
the segment of the shader code in question:
float4 normal = normalize(mul(input.Normal, WorldInverseTranspose));
float lightIntensity = dot(normal, DiffuseLightDirection);
/* lightIntensity causes black coloring. Possible lighting issue or bad normals? */
output.Color = saturate(DiffuseColor * DiffuseIntensity * lightIntensity);
how I am getting my normals:
internal static Vector3 GetNormal(Vector3 VertexA, Vector3 VertexB, Vector3 VertexC)
{
var XY = VertexA - VertexB;
var ZY = VertexC - VertexB;
XY.Normalize();
ZY.Normalize();
return Vector3.Cross(XY, ZY);
}
@hot hazel I found what was wrong: WorldInverseTranspose was not set!
after fixing this, I found that my normals are indeed borked as well, but at least it's showing an attempt here and there
MESALONMESALONMESALON
<@&133522354419662848> ^
question, could this channel be used for suggestions as well? or is it strictly about code issues/questions
im trying to figure out collisions right now. i've got the basic concept down, allowing for walls to stop player movement, but it's hard to implement things such as gravity and floors. whenever the player is colliding with the floor, its horizontal movement is significantly decreased. also, the jump height is always extremely low, no matter how large i set it to. here's a pastebin containing all of the relevant classes/code: https://pastebin.com/jyX0XGDU
im aware that the jumppower is automatically capped to 320, but even so, it seems as though movement covers more distance than jumping (when not colliding with the floor)
not sure if this is too late now
fix to your slow horizontal movement would be to modify this bit
update x first, check bounds and reset x if intersects
and repeat for y
Hello, I've been solo developing a 3D MMORPG using C# with Monogame called Ruin a game inspired by old school MMORPG's like classic WoW,
In just about 7 hours from now, at 7:00 PM AEST, we're diving into a crucial stress test for Ruin. Your presence would mean a lot to us during this phase. If you're available, we warmly invite you to join us and contribute to testing the server.
If your interested I can send you a Steam CD-Key to download Ruin on Steam, we will be meeting on the Ruin discord but its not required to join our Discord.
Thank you in advance for your support!
Ruin's latest update is now live on Steam. Our Stress Test is set to kick off in just 15 minutes. If you require a CD-Key to access Ruin, simply shoot me a message, and I'll be more than happy to provide you with one for downloading.
Hello guys... Can someone help me with tiled?
Maybe give me small idea about on how it works
what about it do you need help with?
there should be tutorials (incl on youtube) on how to use it
Got a nice top down shooter coming out at the beginning of December all written using libGDX framework
hello
Dynamic Weather in Ruin made in C# Monogame, what do you think of this sunset with thunder.
https://www.youtube.com/shorts/t8D3cbajQG4
Does anyone know where can I learn monogame for C# game development
Sprites.
Ui
Animations
Collisions
Physics
Audio
Etc
what guides have you looked at?
collision/physics can get pretty complicated if you want to roll your own, theres libraries to do all of this
There is a guy named code with sphere and challacade . I didn't find anything else
i assume that's on youtube?
Yes
i'd recommend just searching google
Do you mean documentation or what exactly
doesn't seem to be much there
also you will find a good number of ancient tutorials for XNA
those should all generally work (at least if they target xna 4)
But aren't those outdated
I mean monogame had upgrades since then and same goes to C#
K thx
monogame has tried to stay mostly compatible with xna
or at least has happened to stay mostly compatible
idk how much they try at this point
but it was originally a clone of XNA's api
OK. Now I understand. I took a look at the documentation you sent and I believe it is easy to get started with. Thanks
hello guys, I been doing this school project a couple months ago but I am stuck. When I place a troop it is added to an arraylist, then I iterate through it and then I render and depending the type of troop it is I do certain update method:
if (troop != null) {
if (troop instanceof Slime) {
troop.update(fVp,troopArr);
}
else if (troop instanceof Boulder) {
troop.update(fVp,slime, troopArr, tempArr);
}
troop.render();
}
}```
the thing is that only the boulder is being kind of properly updated (the update method is the one who manages the hitbox) but only the last slime has hitbox, can anyone help me?
feel free to ask for more code
Ive downloaded java over and over again but libgdx keeps saying "Java is not installed"
did you download the jdk or the jre?
^
jre
you need the jdk
oh
jdk 21 right?
downloaded it
unziped it and the libgdx still wont detect it ;-;
you need to get the installer version
or install whatevers in that zip file
that will update your PATH environment variable, which presumably libGDX uses
oh im using the wrong site
i did the installer and it still wouldnt detect it , i even put both of their folders in the same folder
you could try restarting your machine, though do you have any logs available?
(I don't use libGDX fwiw so I can't be of specific help)
can someone help me out, I'm trying to set collision data in tiled map editor and load it using box2d but I'm getting weird results.
relevant code :
MapLayer collisionLayer = tmap.getLayers().get("Collisions");
for(RectangleMapObject rectangleMapObject : collisionLayer.getObjects().getByType(RectangleMapObject.class)){
Rectangle rectangle = rectangleMapObject.getRectangle();
BodyDef bDef = new BodyDef();
bDef.position.set(new Vector2(rectangle.x, rectangle.y));
bDef.type = BodyType.StaticBody;
Body body = world.createBody(bDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(rectangle.width, rectangle.height);
body.createFixture(shape, 0.0f);
shape.dispose();
}
same level in tiled editor
SetAsBox takes half sizes looks like
so you need something like var hw = rectangle.width / 2; var hh = rectangle.height / 2; position.set(new Vector2(rectangle.x + hw, rectangle.y + hh)); ..setAsBox(hw, hh);
^
thank you
stoozee thanked cobalthex
Do you have a game Idea or a reference you’ll like to bring to reality?
I’m available to work with you for your game developments
?
to monogame?
if yes, monogame is not an engine so you will be doing a lot more work by yourself
yes it is easy
does anyone know to how make sprite rotate around another sprite in monogame
i am trying to remake pop the lock game
as in orbit another sprite?
var currentOrbitAngleRadians = MathHelper.PiOver2;
var orbitPosition = centerPosition + new Vector2(
MathF.Cos(currentOrbitAngleRadians) * orbitRadius,
MathF.Sin(currentOrbitAngleRadians) * orbitRadius);```
how do i make it move
animate currentOrbitAngleRadians
currentOrbitAngleRadians += (gameTime.ElapsedGameTime * someSpeed) % MathHelper.TwoPi;
then how does it move
orbitPosition would be your sprite's position
k
centerPosition is what you want to orbit around
k now i understand
not moving
float orbitRadius = 135f;
float currentOrbitAngleRadians = MathHelper.PiOver2;
Vector2 orbitPosition = Centre + new Vector2(
MathF.Cos(currentOrbitAngleRadians) * orbitRadius,
MathF.Sin(currentOrbitAngleRadians) * orbitRadius);
currentOrbitAngleRadians += speed % MathHelper.TwoPi;
this is the code
you have to save currentOrbitAngleRadius somewhere where it won't be reset every frame
if you're going clockwise, angle is currentOrbitRadiusAngle is + 90deg, if you're going counter clockwise is -90
90 deg = MathHelper.PiOver2
I recommend studying up on some trigonometry for this
equation?
i just told you
so i convert currenOrbitRadians to angle then add 90
and if anti clockwise i subtract 90
?
ok thanks it works now
So I am currently trying to enhance my abilities in monogame so I am planning to make a 2d shooter game where the player is in middle of screen and you rotate him and shoot enemies that spawn randomly and move toward player . I plan to try implementing UI and a Particle system so is it better to just watch a tutorial for them first or try experimenting first and figure it out then watch a tutorial as a refinement . Any thoughts?
Experiment
You'll learn a lot more
OK thanks
Texture2D.FromStream/FromFile
Monogame.Extended has a shapes library IIRC
xna is a wrapper around directx, directx doesn't do shapes, its up to you to implement that.
Two of the ways you can do it:
- Create a 1x1 white pixel texture (new Texture2D() then texture.SetData() ), stretch that to whatever size you want
- Draw primitives and use a shader to fill in the color (you probably will want a custom shader here)
it can go in any folder you want
visual studio can be a bit weird with the working directory, but when running an app, by default, the working directory is the location the exe is in
so if you say FromFile("foo/bar")
foo is relative to that working directory
^
I'm gonna ask for libgdx help here
Oh wait monogame is an engine :(
I was going to try and make an engine in mono game
got this far
experiencing a horible bug
dont ask just to ask, ask
not an error, a bug
Im trying to get it were wasd is local space
and not worldspace
the video is in world space were w is on the world grid instead of where im looking
Yep, I was trying to tell you here 😅 #gamedev-chat message
You have to construct a new vector from the camera rotation to get the 'forward' direction
And then scale it based on your W/S movement
so I have to quit and do everything in opengl
You don't have to
Using MonoGame is still 100% fine
but its a game engine
Is that a problem?
yes
monogame is a framework not an engine
ok now im even more confused
thats what I said originaly
but both he and this said it was an engine
well that's just 'somewhere to put it'
I would have put it under other dev
¯_(ツ)_/¯
Why is it a problem?
It's open source, pretty mature and has a decent community
because you cant make an engine in an engine
you arguably could, though it would be silly
but yes monogame is a framework not an engine, perfectly suitable for diy
well I might be switching to silk.net or the C# version of opengl (I forgot the name)
I was right hehe
what do you mean join all the pieces?
as in not having to combine the meshes into one?
yeah
whats causing you trouble?
ok, what are you trying? I understand they're all rendering on top of each other
trying to make it look exactly how it is in blender
i need more technical detail...
typically for transforms you either use matrices or something like qual quaternions
what more can I give
what hav you tried?
where are you getting stuck?
are you looking for help?
yes
a lot but nothing specific
well as I mentioned above, typically you use recursive transforms via matrices or dual quaternions
if you have Root > A > B > C > Leaf
Root has the world transforms, A = root * A's local transforms, B = A * B's local transforms, etc
(maybe reverse order for multiplication)
?
My first game in its infancy
It took me WEEKS to get block rendering to work. Resorting to ChatGPT was my only option lmao I hate the tutorials for LibGDX
For those who want to see a scope for the game, I'm going for a sort of Terraria clone (Big But Principle incoming) BUT, it's top-down like the OG Zelda, and there are sort of "levels" (caves, underwater, etc.) to a procedurally generated world. Here's my TODO list:
Anybody experienced with 3D Engines in XNA? Got a Voxel Engine generating trees, however, it only generates the leafs and not the trunk for some reason.
The code, I've tried adjusting the trunk height and a bunch of other options, but can't seem to figure out what's going on
do you have any debug drawing capabilities?
Hmh good one, unfortunately no. I'm not that experienced just yet but will look into that.
i recommend adding stuff like that where you can draw debug lines/shapes in-scene
Will do that 😉 Thanks for the suggestion
my end goal is to end up having my game look something akin to this, but I have no real experience dealing with graphic code. Can this look be achieved purely through HLSL?
I know MonoGame has the Effect class, and the Basic Effect seems to do some nice stuff. But I dont know if an Effect of an FX file is the right way to go about making a look like this
can someone please tell me what's wrong with the load method in player
it keeps giving me that _animPlayer is null
your load method is static
likely an order of operations issue
esp since you're creating a new anim player for every instance
yea cuz I’m using it in another program
Is it not supposed to be
that is for you to decide, but it doesn't really make sense how you're doing it now
How would u normally do it
either pass in the anim player, or move it into the consturctor
god damn i was so dumb
ty i finally know the hell i was doing
What's this channel for
it's in the name
What's Monogame and Lib GDX?
game libraries
They're simpler than engines but provide some os abstraction to make it easier to get up and running
The helpful part is you're not stuck with the systems that they put in
You can also access a lower level system whenever you want
So you can mold it yourself if necessary
Let's collaborate. It's easy for me to fix game issues, and also I found it super convenient to develop a new game
<@&133522354419662848> is this allowed or nah ther3s alot of it in this server tbh
Hello
hi
Happy New Year!!!!!!!!
<@&133522354419662848>
Hi
hi felix!!
what do you mean using another medium?
alright peeps: I'm lacking a bit of common sense I guess, but I was fairly sure this code would work. I'm missing a calculation, could someone point me to what I'm missing:
Vector2 origin = new Vector2(x, y).add(weapon.bulletOrigin).rotateDeg(rotation);
Vector2 target = new Vector2(worldMouseX, worldMouseY);
What are you trying to do?
Well it's fixed now but I just wanted the bullets to be shot from the top of the weapon as I rotated. I just wanted taking into account the origin of the player
Does anyone have a good way to familiarize me with LibGDX please?
practice, read existing code
After i exit my Game there is a white screen and it seems like Lib.gdx is closing but the App is still active. I use first Gdx.app.exit(); and after that System.exit(0). Someone have a solution for this?
Found a way, just had a wrong Interface for System.exit(0)
hello
hello
so were not gonna talk ab how this person has a cursor on his phone?
plug in a mouse
Could also just be an emulator
hello
Hi
<@&133522354419662848>
monogame love and support
<@&133522354419662848>
How can I work with custom devanagari fonts? Tried with the normal spritefont method but the complex conjuncts seem to be broken and it doesnot look good.
for monogame? You will likely need to write your own spritefonts or modify the monogame one to support the character ranges you need
Yep, had to do that. Did it with the help of HarfBuzzSharp and SkiaSharp and it worked!
Hey does anyone have experience with libgdx? Would you recommend for a small game
sure
Monogame engine library and project using that library commits so far
Converting a .bat file game to monogame. Time to rewrite 14755 lines
That's a job for AI.
oh?
hello
Hi, How are you?
After trial and tribulation of having to swap how my renderer handles ui calls, I now have some nice ui loaded in from json!
Testing out resource ui feedback, big fan of this but def need to add a setting to disable it lol
flickering was from layerDepth being too similar
Added grass particles when spawning the grassy wassy and changed color of point trails
https://imgur.com/vAWd1BA
rewriting my silly tetris clone from the ground up
one day I will work on real projects
cool new effects (again)
kool kounterz
sounds
Anyone use skeletal 2d animations? I've realized there doesn't seem to be basically any tutorial or actual way to do this within the past 5+ years lol
hasn't really changed 😛
it's not any different from 3d skeleton stuff fwiw
If you're going to go through the effort of rigging a 2d sprite for animation, you might as well learn full 3d rigging and animation. You get the added simplicity of any angle. https://github.com/chrishayesmu/Blender-Spritesheet-Renderer
that's pre-rendered animation, not the same thing as in-game skeletal animation
Right. Another thing worth mentioning is that Spine is proprietary software with a relatively constrictive license. You can only use it on 1 computer at a time and costs $369 per year for the "full" product. If a developer is just starting out, it is worth it to consider low poly blender animations, especially if their game is not a left-to-right platformer.
<@&133522354419662848>
Not much depth to this kind of game. I prefer asteroid-like controls where you can move in any direction.
Random zigzag up a mountain. Width of the passage varies too. Padding on the left and right.
You mean this style ?
Like this. This game even has split screen multiplayer! Absolutely amazing game.
"fully" working menu, oml took a while
🚀✨ If you’re into a charming, fast-paced space shooter, take a look at my game — cute sprites, polished visuals, and just the right amount of challenge. It might be exactly the kind of adventure you love playing! 💫🎮
How to learn libGDX?
tutorials and reference guides?
is there any better way to have fonts in lib gdx than the bit map ones? Bitmap fonts are practically obsolete for ttf files and the always show up blurry unless i used a large image size
I can't speak specifically to libGDX, but rendering vector fonts is expensive, so even if games use them, they often get pre-rendered to character atlases on startup/demand
Yes
👋
👋
there's an active libgdx discord, check that out. As far as blurry fonts for libgdx, there are several causes and fixes. If you ping on the libgdx discord you should get a solution.
I have bitmap fonts in my libgdx game and they work well, small and large size. I recall having some difficulty and had to make some tweaks. I don't remember exactly but if you're still having the issue we can help on the discord.
Hi guys, I have a question. As an artist with absolutely 0 coding knowledge and experience, how hard would you say monogame is to learn?
I recommend starting with something like unity
ooh, even for pixel games similar to stardew valley/dave the diver?
it's probably a bit overkill but you could
monogame is pretty approachable, but you'll need to learn c# first.
monogame is only a framework, an engine like unity does a lot more for you
there are also simpler 2D engines as well like game maker ( #gms-dev )
that said, I really enjoyed monogame (XNA at the time) but it does require some programming practice
ohh I'll check out game maker too, I'm planning on learning to make a 2D pixel game similar to maybe chef rpg or dave the diver
Man, I have never touched gamemaker before.
I kinda have an open source policy tho
Monogame.Extended adds pretty much anything an engine does for you.
i wouldn't say everything, but a good amount of stuff
i mean what doesnt it add?
it doesn't really provide a full rendering pipeline
also is only really catering to 2D
there's no multiplayer stuff, which is required for some games
then again I have never really made anything in Monogame so...
Most frameworks dont implement multiplayer anyways
yes, frameworks != engines
I see what you did there!
I generally use frameworks for small projects while engines for bigger ones
also the input system doesn't extend to more high level gameplay concepts
what are "high level gameplay concepts"
oh ok
I have never made a game that has combo attacks, so i wouldnt know anything about that
libgdx FTW
we've got a game on Play Store, ios soon once we fix some ios specific bugs. For those who want to de-couple from an IDE, go totally opensource, and just write code, LibGDX is a great option.
good support from the libgdx discord also.
Using it rn, gotta say im enjoying it so far
Esp scene 2d ui stuff
Very useful
Hey stoozey, i was thinking to make tools for libdx or monogame do you have any suggestions

No no don do that. Make a monogame/libgdx like lib in c++
Another thing i like abt libgdx is the tools like skin composer and texture packer, very useful
Maybe u can make those for something like raylib
Or maybe they alr exist but idk lol
there's a pretty active discord for libgdx, you could ask there.
Libgdx needs more beginner friendly tools IMO.
<@&133522354419662848>
If you prefer to be an artist first and foremost, then don't even consider MonoGame. Use Unity or Unreal.
I'm trying to draw my player at an angle, but whenever I do this it shows up as a black box
I've looked up and down but nothing seems to work
we're going to need more detail than that
I ended up fixing it, it was the content pipeline on monogame just not updating for some reason
hey so i'm trying to make my game window maximize itself upon launching using system.windows.forms and its control.fromhandle method, but for some reason that method isn't working and it's only returning null
how can i fix this?
(this is monogame btw i have no idea what lib gdx is ^^")
i believe the window does not exist yet
add an event to graphics.DeviceCreated
check there
well that's the thing, it does it no matter where i grab it at, even during runtime
like in the update method somehow
i have the same setup in another project and it seems to work fine
but uh yeah i tried that and it does seem that the graphics device is created
:D
what
a bunch of hexadecimal stuff that i don't understand
im going to guess there is not an associated windows form
try
add [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); to your main cs file
in the class
wait where? that's some weird lookin code
and then somewhere in the code ShowWindow(Window.Handle, 3)
just at the top of whatever class this code is in
oh it's erroring me, saying that dllimport, marshalas, and unmanagedtype couldn't be found
add using System.Runtime.InteropServices; to the top
okay did that, what's supposed to happen?
oh, if it helps at all, i did set this project as cross-platform opengl
if its running on windows this will work
linux/osx use their own mechanisms for maximizing a window
(you can probably find a cross platform library that takes that window handle, if its an issue)
store the return value in a variable
whats it returning
also try calling it in different places
see if it makes a diff
false
try putting it somewhere later in the code then
nope, always false
not exactly
i have this event method for checking if the window size has changed and then setting the aspect ratio accordingly
protected void ClientSizeChanged(object sender, System.EventArgs e)
{
Window.ClientSizeChanged -= ClientSizeChanged;
if (Window.ClientBounds.Width > 2 * Window.ClientBounds.Height)
{
graphics.PreferredBackBufferWidth = 2 * Window.ClientBounds.Height;
}
else if (Window.ClientBounds.Width < (4.0 / 3.0) * Window.ClientBounds.Height)
{
graphics.PreferredBackBufferWidth = (int)((4.0 / 3.0) * Window.ClientBounds.Height);
}
graphics.ApplyChanges();
Window.ClientSizeChanged += ClientSizeChanged;
}
yeah
not sure then
the only think i can think of is the platform setting, since this one's cross-platform and that other one was windows only and it worked on that
ShowWindow should be able to maximize it whenever called
though i guess it might not work
because the windowHandle you're getting is not the actual window
but some intermediate representation
like opentk/whatever
wait that actually helps a ton
i just need to figure out how to get the actual window then, right?
in theory
you may wish to browse the monogame source some
figure out what that handle is
alright i'll do that tomorrow then, it's almost 2:30 am lol
thanks for the help @hot hazel!
Axonium gave karma to CobaltHex
man this feels really weird asking a question twice in a row after coming from the way more active #unity-dev, but how can i implement parallax scrolling for my background (i.e. making it move at a different speed)? i have my own method for making it wrap indefinitely, as for some reason the linear wrap samplerstate isn't working for me:
protected void DrawBackground(Texture2D sprite, SpriteBatch batch)
{
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
batch.Draw
(
sprite,
new Rectangle
(
(int)((Math.Round(cameraX / 1920) + i) * 1920),
(int)((Math.Round(cameraY / 1080) + j) * 1080),
1920,
1080
),
Color.White
);
}
}
}
some notes on that: cameraX and cameraY are always negative (the opposite of what they are visually) for some reason, and the viewport resolution is technically always 1920x1080 due to the spritebatch using the "cameraMatrix" variable in this code block:
float scaleX = (float)Window.ClientBounds.Width / 1920;
float scaleY = (float)Window.ClientBounds.Height / 1080;
Matrix scaleMatrix = Matrix.CreateScale(scaleX, scaleY, 1.0f);
float xDif = cameraX - (ships[playerIndex].Position.X - 960);
float yDif = cameraY - (ships[playerIndex].Position.Y - 540);
cameraX -= 0.1f * xDif;
cameraY -= 0.1f * yDif;
Matrix translationMatrix = Matrix.CreateTranslation(-cameraX * scaleX, -cameraY * scaleY, 0);
cameraMatrix = scaleMatrix * translationMatrix;
so i really can't seem to wrap my head around how to use something like a "parallaxSpeed" parameter in that drawbackground method
there is a lot of hard coding happening here
anyway if you have a map position
parallax position = mapPosition * 0.5
you should not hard code window size into your game
at least anywhere past where its set
window size can still be whatever you want within reason, but it's going to be a 1920x1080 one scaled down (or up) to keep it consistent
like if you set the window size maximized on a 4k monitor or something, it wouldn't be balanced to zoom the camera out because of that
anyways, what does mapPosition mean?
(update to my question: made a change to the drawbackground method to make it much more readable; instead of calling 9 instances of batch.draw individually, it just uses two for loops now)
(even more updatez to help with anyone that wants to answer: reworked all doubles to instead use floats to keep things consistent, changed player pos to a vector2, and made the camera pos no longer the opposite of what it should be)
well it's a bit too big to fit onscreen so you'll have to excuse my shoddy mspaint visualization
but it's a grid so that it can loop forever seamlessly, i know that i can minimize it to a smaller number (1 to 4 depending on how many should be onscreen) but i'm not really trying to go through the mental gymnastics of calculating that right now
what are you drawing in that pattern?
i mean it's just a generic star background i got off the internet, dunno why that's important at all
just trying to visualize what you're doing
here; notice how the stars (most visibly the large ones) wrap to the other side of the screen once they go offscreen
you can much more easily do this by using a wrapping texture
set GraphicsDevice.SamplerState to one of the wrap modes ( https://docs.microsoft.com/en-us/previous-versions/windows/xna/bb198798(v=xnagamestudio.42) ) when drawing the bg
😀
i said specifically that that wasn't working with my scaling method for whatever reason :/
if i set it then the background just doesn't show up
render the texture at 2x the size of your window
then draw it at -(playerPosition % windowSize)
multiply those numbers by your scale
(you can do this via a matrix)
your scale may be wrong
well it wasn't even showing up last i tried that so maybe it was the position as well?
either way i don't know what these variables mean, i'm not using the player's position but the camera's position and i'm not sure if windowsize refers to 1920x1080 or the actual size
and the camera position isn't the opposite of what it should be anymore so i don't know about that negative
player position = camera position
yes
window size is whatever the viewport size is
so GraphicsDevice.Viewport.Width/Height
okay, so i feel like i'm almost there? just don't really know how to multiply the rectangle by the matrix i'm using
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap);
spriteBatch.Draw(assets.GetSprite("stars"), new Rectangle((int)-(cameraX % GraphicsDevice.Viewport.Width), (int)-(cameraY % GraphicsDevice.Viewport.Height), GraphicsDevice.Viewport.Width * 2, GraphicsDevice.Viewport.Height * 2), Color.White);
spriteBatch.End();
(side note, assets is just a class i made with dictionaries and methods to grab a sprite or sound effect by its filename)
okay yeah i have no idea what i'm doing 😀
i really do not like having to work with rendering without using that matrix as the transformmatrix of the batch itself
but i know for a fact that the modulo operator is definitely what i should've been doing
okay back for another day of this, i really think that this is overthinking it
i don't want to have to rework my entire system and i really shouldn't because this is not what i'm trying to do
i had a method that worked the way i like and i just want to be able to use parallax speed with it
not sampler states, not messing with what the viewport size actually is, none of that
i'm sticking with this
protected void DrawBackground(Texture2D sprite, SpriteBatch batch, float parallaxSpeed = 1)
{
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
Rectangle rect = new Rectangle
(
(int)((Math.Round(cameraX / 1920) + i) * 1920),
(int)((Math.Round(cameraY / 1080) + j) * 1080),
1920,
1080
);
if (!Rectangle.Intersect(rect, new Rectangle((int)cameraX, (int)cameraY, 1920, 1080)).IsEmpty)
{
batch.Draw(sprite, rect, Color.White);
}
}
}
}
that's final. i just want to know where to throw that parallaxspeed parameter into that rectangle constructor
even then, it's not drawing 9 times anymore, only up to 4 because i remembered that rectangle.intersect is a thing
as a metaphor, i shouldn't have to replace my whole car just because i want a better radio
lol
im just joking
btw you can use rect.Intersects(new Rectangle(...)) rather than rectangle.intersect().isempty
oh, i knew that existed but i tried doing it from the static rectangle class like rectangle.intersect() so it wasn't showing up
okay, progress!
i ended up doing
double normalX = (Math.Round(camera.Position.X / camera.Resolution.X) + i) * camera.Resolution.X;
double normalY = (Math.Round(camera.Position.Y / camera.Resolution.Y) + j) * camera.Resolution.Y;
double offsetX = parallaxSpeed * camera.Position.X;
double offsetY = parallaxSpeed * camera.Position.Y;
Rectangle rect = new Rectangle
(
(int)(normalX - offsetX),
(int)(normalY - offsetY),
(int)camera.Resolution.X,
(int)camera.Resolution.Y
);
thing is though, it doesn't extend forever if parallaxspeed isn't 0
(as evident through where it cuts off at its top in that video)
https://streamable.com/lx207 heck yeah, solved
double offsetX = (camera.Position.X * parallaxSpeed) % camera.Resolution.X;
double offsetY = (camera.Position.Y * parallaxSpeed) % camera.Resolution.Y;
if (offsetX < -camera.Resolution.X / 2)
{
offsetX += camera.Resolution.X;
}
else if (offsetX > camera.Resolution.X / 2)
{
offsetX -= camera.Resolution.X;
}
if (offsetY < -camera.Resolution.Y / 2)
{
offsetY += camera.Resolution.Y;
}
else if (offsetY > camera.Resolution.Y / 2)
{
offsetY -= camera.Resolution.Y;
}
is there an easier way to apply AA in monogame than getting an AA shader and applying to a rendertarget?
do you mean antialiasing? if so, i found this: http://community.monogame.net/t/solved-anti-aliasing/10561
ah, don't know what to tell you then :/ it does seem like using shaders isn't the recommended way of doing it though
do you have any idea why that solution's not working?
not really
I'm fairly certain it's working
like
the code is running
but it's just not doing anything
what platform are you building for?
oh
yeah opengl kinda tends to break everything in my experience
would it be possible at all for you to move your code and assets to a project on another windows option? such as the directx one
since there doesn't seem to be any real easy way of converting an existing project to another option
@sturdy prairie you're likely turning AA on and not applying the changes to the gfx device
if you do it in the Game1 constructor, you can be sure that it takes effect
I'm doing it in the game constructor yes
Hello, im Using Monogmae w/ Xamarin & im trying to get this tutorial working for Android:
https://www.youtube.com/watch?v=CcPb0bKkpeg&list=PLHJE4y54mpC5hrlDv8yFHPfrSNhqFoA0h&index=2
The thing is when im trying to load the image I get an error of not finding it
public class SplashScreen : GameScreen
{
Texture2D image;
string path;
public override void LoadContent()
{
base.LoadContent();
path = "WowperroFirmaWhite.xnb";
image = content.Load<Texture2D>(path);
if (image == null)
{
image = content.Load<Texture2D>("WowperroFirmaWhite.png");
}
}
In other part of the code I also have
public class GameScreen
{
protected ContentManager content;
public virtual void LoadContent()
{
content = new ContentManager(ScreenManager.Instance.Content.ServiceProvider, "Assets");
}
How do u know which path to use w/ Xamarin
Pls help I´ve been stuck here for a while unu
please @me if you read this & know the answer
your path is wrong
Ok, but I have a question, does the path acts the same if using Xamarin?
i dont know xamarin, but if you are getting a path not found, i would start there
with c# can u create a .txt file like w/ c++ to know where the program is searching?
like without specifieng a path
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
like this but w/ c#
it's all reference, you gotta start from somewhere, just hardcode the path and see if it gets past the error, if it does, then work our how your file references will be, if it doesnt then you got other issues
in C# look up FSO
@manic granite System.IO.File.AppendText("example.txt", "Writing this to a file.\n");
or something like that
or System.IO.File.OpenWrite/new FileStream(...) -> stream.WriteBytes/whatever
or even new StreamWriter(file) -> writetext/whatever
plenty of options
Thx for all the assist, In the end I did not know what was happening, but it said acces denied, But i have fixed the path problem, thx
can anyone suggest how I can implement multiple scissors in libgdx, I am trying a window like feature where the character is only visible inside the window and is clipped outside
change the scissor rect per call. or use a different method
like depth/z buffer
or alpha testing
or good old math
^ this, alot of different ways to approach it
thanks @hot hazel , i tried depth clipping, it worked
kamlesh457 gave karma to CobaltHex
Hey, I know this is opinion-based but what aspect ratio should I design my game under?
What I'm making is not much of a game, and more like a typical app.
I have a single background image that should be shown on any aspect ratio without black bars.
Looking at StackOverflow, answers seem to lead to designing for 16:9 (most common aspect ratio for android phones).
Therefore I downloaded a 1920x1080 background image.
Since I don't want black bars, using FitViewport is out of the question.
I decided to use either ExtendViewport or FillViewport. Testing both, FillViewport seemed to be the better result.
ExtendViewport still had a bar when running on a different aspect ratio than designed.
FillViewport didn't have black bars at all, but it still had one issue.
Running the app on a 16:9 screen showed the image perfectly (as expected). However, running it on a screen that's wider, such as a 1800x2560 tablet, results in the picture being extremely zoomed in (also a bit expected considering that's what FillViewport does).
Instead of trying to get assets for 16:9, should I find a background that would fit wider resolutions so that it doesn't look extremely zoomed in? I can't figure out how to scale to different aspect ratios properly even though Viewports should be making it easy for me.
Shoot for an actual target device. If it's PC, yeah stick with 16:9. Lots of android and ios devices have 16:9 or 16:10. Switch is 16x9.
Just for some examples
@jagged slate ok thanks! what viewports do you tend to use? would extendviewport be best for game objects, and fitviewport for the user interface?
stackoverflow answers tend to lead to fitviewport the most but i really don't want black bars if possible
winter is coming gave karma to Kipling
indeed, it's all driven by device
most PC games allow the user to choose all supported or a large set of available card/gfx drive resolutions and color depths
if i want to support a set of aspect ratios without black bars, will i need to have a set of assets for each of those aspect ratios?
e.g. a wider/shorter background for 4:3 and a thinner/taller background for 16:9?
for now i'm just going to design it for 16:9 but even with viewports it still feels off
depends on your D
alot of games, just rescale
i theory, people only play in a certain aspect ratio at different sizes, so in theory, you 2d resources dont scale, but your background layers and such, should show more
also, there is no rule, that says, you have to support multiple
i just read about mipmaping so i'll just be using that instead of having to manually resize images for different resolutions. i'm definitely gonna have to find a bigger background that can show more if a wider screen is used
thanks @reef light!
winter is coming gave karma to TormentedGothicPrincess
i wouldnt provide different resource sizes, use code to ratio up or down
major of games will only provide 1 (hires) or 2 (high/lowres) textures/resources
TGP's experience is similar to my own. Also I've heard of doing some cool things with having device info pulled on download and then pulling down textures of specific sizes afterward to match so you don't have to resize
Yo, i´m tring to download an apk to my phone (Xiaomi Redmi 6) the apk is generated w/ monogame in visual S 2019, i have the xamarin emulator & i can make it run on it, but when I pass the apk to my phone I get this error java.lang.exception: Unable to get provider Any ideas?
Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="testandroid.testandroid" android:versionCode="1" android:versionName="1.0">
<uses-sdk />
<application android:label="testandroid"></application>
</manifest>
And here is the error
java.lang.RuntimeException: Unable to get provider mono.MonoRuntimeProvider: java.lang.RuntimeException: Unable to find application Mono.Android.Platform.ApiLevel_27!
at android.app.ActivityThread.installProvider(ActivityThread.java:6407)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5909)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5826)
at android.app.ActivityThread.-wrap1(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1708)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6662)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.RuntimeException: Unable to find application Mono.Android.Platform.ApiLevel_27!
at mono.MonoRuntimeProvider.attachInfo(MonoRuntimeProvider.java:38)
at android.app.ActivityThread.installProvider(ActivityThread.java:6395)
... 10 more
Caused by: android.content.pm.PackageManager$NameNotFoundException: Mono.Android.Platform.ApiLevel_27
at android.app.ApplicationPackageManager.getApplicationInfoAsUser(ApplicationPackageManager.java:381)
at android.app.ApplicationPackageManager.getApplicationInfo(ApplicationPackageManager.java:363)
at mono.MonoRuntimeProvider.attachInfo(MonoRuntimeProvider.java:35)
... 11 more
Disable Use Shared Runtime from Project ->Options->Android Options.
I know little about mono on android, but if that ^ doesn't work, try
https://developercommunity.visualstudio.com/content/problem/443515/unable-to-build-valid-marshmallow-app.html
Thx a lot guys, the first option worked for me
now im stuck w/ screen size, 😦
Anyone that knows hoe to get the screen size, cause when I build, & pass it to my phone, it does not look good
public class Activity1 : Microsoft.Xna.Framework.AndroidGameActivity
{
public static int ScreenHeight;
public static int ScreenWidth;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
var g = new Game1();
SetContentView((View)g.Services.GetService(typeof(View)));
ScreenHeight = (int)(Resources.DisplayMetrics.HeightPixels); // Resources.DisplayMetrics.Density);
ScreenWidth = (int)(Resources.DisplayMetrics.WidthPixels); // Resources.DisplayMetrics.Density);
g.Run();
}
}
ScreenH & ScreenW
It works /w Xamarin VS & Monogame
Srry dont´know
@manic granite you shouldn't set resolution when building for android
Then, where should I get resolution?
@manic granite you can get the backbuffer size from the graphicsdevice
@manic granite you can use
[Game.GraphicsDevice.Viewport]
your stuff will be [ClientBounds] and you can get the availables from [GraphicsAdapter.SupportedDisplayModes]
if you wnat the actual window size. GameWindow.ClientBounds
if you want the size that your game will render to, backBuffer width/height
viewport by default will match that size, but not required to
anyone gradle pros know whats happening here?
better screenshot
I'm just trying to run the basic libGDX application in HTML the way you're supposed to
so if anyone has a libgdx game that works in HTML, could you help me out to figure out why yours is working..?
(this is while trying to run superdev btw)
I got a bit further
Is it supposed to look like this? It doesnt look like my game at all...
It's supposed to be loading in your assets. After it's done loading it will start running your game.
For example: https://pjrader1.itch.io/bouncy-bullets
It was with the viewport, thx for all the help,
For libgdx, I get some weird error saying something about a bad version 57?
When I'm trying to use their builder .jar file
Anyone know what that is about?
Make sure you have the latest JDK installed and that it's in your path. Usually an error like that is that your environment Java version is lower than the version of LibGDX's builder.
hmm now for whatever reason I get an invalid package name error
yeah I still get General error during semantic analysis: Unsupported class file major version 57
java --version
java 13.0.1 2019-10-15
Java(TM) SE Runtime Environment (build 13.0.1+9)
Java HotSpot(TM) 64-Bit Server VM (build 13.0.1+9, mixed mode, sharing)
Seems like libgdx doesn't work with java 13
Feel like that should be a huge disclaimer on their site
Strange, Java is meant to not have breaking changes like that. If it worked on a lower level of Java it should run on a higher version no problem.
Real shame, I wanted to give it a try, but can't even install it
Google doesn't even return anything
Are you double-clicking it or are you running it through the command line?
Yeah that's the only thing I found but I didn't know if that's the issue you were having
I guess the pointed question is: How do I tell the LibGDX setup jar file to use gradle 6.0
Seems like it doesn't use system level gradle, cool.
I wonder if when you click Generate if it puts the files in the destination folder
And just run gradle yourself
It does indeed, I tried to fiddle around with the project but I can't upgrade gradlew
Yeah, I'd just delete gradlew and see if it'll build with your installed Gradle. Although from version 5 to 6 there might be breaking changes who knows
Might have to grab a different lower version of gradle.
I have gradle 6.0 available
Or, just install an older JDK lol
Do you know the older version number?
Eh, now that I'm thinking about it it probably won't work
Cause at the end of the day you still have JDK 13
Damn, well RIP libgdx
Try Gradle 6 first, no harm in trying since it's already installed
i tried gradle desktop:run but says that command wasn't found
Try just gradle
The generator runs gradle, don't know what task but it downloads a bunch of dependencies. It might need that to get the desktop:run to work, but I'm not sure. Never had this trouble of course.
wow it worked
(more question details if necessary: https://www.reddit.com/r/libgdx/comments/e3tqfd/is_it_possible_to_compile_a_libgdx_game_for_html/)
You can use JavaScript in GWT with a little work: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsOverlay.html
Is GWT similar to Socket @pearl ore?
Would I have to make notable changes to my code base? (converting certain data types to bytes isn't notable)
GWT stands for Google Web Tookit. Basically, it's a compile target for Java (turns Java into JavaScript). This is how LibGDX is able to run as an HTML app, it essentially transpiles your code into JavaScript. Since it's turning Java into JavaScript anyway, you can use JavaScript code if you wrap it. That means that you can use any JavaScript library, including socket.io. It involves a little work, you have to create a Java wrapper around your JavaScript code.
So I would have to make a Java class that wraps the JS Socket.io library and make method calls to that instead?
If that's the case I'm not sure how to go about doing that.
The documentation I linked explains the basic process, it's just a matter of reading and figuring it out. There's also a couple Google I/O presentations that are pretty helpful.
Or you can see if you're lucky and see if someone has already made one for socket.io.
just as I'm reading, couple questions
- I need to install JSNI (as a module/library), right?
- Is my goal to turn all the Socket.IO classes into JavaScriptObjects?
@pearl ore
I finished reading, from what I understand I must
- Find the JS version of the socket.IO library (currently, I have the Java version)
- For the classes I want to use (Socket, IO and Emitter), I have to make a Java class that extends JavaScriptObject so I can communicate with them
- In my code, replace the socket.IO native classes references with my new Java classes
What I don't understand is step 2 (sorry for the pinging @pearl ore do tell if I'm being annoying)
Wait, is it just as simple as doing this for every class and putting in the correct namespace?
Something like this?
Have I got this right @pearl ore
im not fully certain this makes sense
One thing I don't understand is what html:dist is going to do. The only way to call socket.io methods from any language would be to compile the module, and when I tried it fail. If I compile the Javascript version of the module, GWT will notice it's JS and not try to transform it to Java code? because from what I understand that's what it doesn't manage to do. Do I understand the problem correctly?
Side Question: is there a library similar to Socket that works with GWT?
also could I just use that? i dont have time to test it but would it solve my problems?
Seems right to me. It's been a long time since I've used GWT, I can't recall off the top of my head how to the JavaScript to interface directly. When you run html:dist it's going to compile your game in Java to JavaScript using GWT. There's a configuration file in the 'html' module that you have to configure at the very least. LibGDX has good documentation, and GWT has been around for a while so it'll just take some hard searching to find what needs configured.
As far as using another library, there's the one you listed. Depends on if you absolutely need socket.io or not. There are also ones for websockets instead.
@pearl ore I've heard people say that if I want to do this and have the game run in the browser, I CATEGORICALLY need to use websockets
I hope that's not true
I made some progress trying to make the GWT_Socket.io compile correctly but boy importing modules correct isn't easy
socket.io is a wrapper around websockets nowadays. There is RTC but I'm not sure if that took off or not.
@pearl ore man this was a slow day for me... Am I supposed to implement the JS Socket.io code as a library or as a module in my project's core?
Oh, well in your core you can define an interface and pass it as a parameter to your main game class. Each platform you have to supply an implementation of the interface. In your html project you can implement it using JavaScript.
Something else that might help, and I didn't know about this, you can write JavaScript as Java native code, so there's that: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html
okay so for the part that I understand, aka the Java distribution of Socket.IO
The non-HTML implementation of the interface that abstracts away for me all needs of instantiating Socket.IO classes like Socket or Emitter instead has its own methods that the core code will call (and IT instantiates those objects)
so for instance I could turn the code
data.put("x", player.getX());
data.put("y", player.getY());
data.put("rot", player.getRotation());
socket.emit("playerInit", data);
into
SocketIO socketInterface = new SocketIO(whatever is needed here);
[...]
socketInterface.emit("playerInit", {"x", player.getX()}, {"y", player.getY()}, {"rot", player.getRotation()});
and in the socketIO implementation for non-HTML it would look like
public void emit(String event, Object[] ... args){
JSONObject data = new JSONObject();
for(Object object : args){
data.put(object[0], object[1]);
} socket.emit(event, data);
}
(JSONObject is also something GWT had trouble compiling so that's why I abstract it away)
So far am I correct @pearl ore ?
Little hard to read so here's a little pseudocode to illustrate (might be what you had in mind idk):
core:
interface INetInterface {
void sendEvent(string event);
}
...
INetInterface netInterface = ...; // Some implementation supplied by the `html` module
netInterface.sendEvent("foo");
html:
class HTMLNetInterfaceImpl implements INetInterface {
public void sendEvent(string event) {
js_sendEvent(event);
}
private static native void js_sendEvent(string event) /*-{
// Regular-old JS here to call socket.io directly
socket.emit(event, {});
}-*/;
}
Okay, I do believe that's what I'm doing!
👍
Almost done with the GWT-friendly implementation
I'll get back to you if I have trouble with the non-GWT implementation
also
/*-{ }-*/
I discovered this notation today and... it's not a comment? 
It is
It's just that the GWT compiler specifically is looking for it and will recognize that you want the contents to be treated as JavaScript
Some project, can't remember the name, lets you do the same thing with C++ which is neat. Creating native wrappers can be a pain sometimes.
Currently going over the part of my code that set all the Socket.IO callbacks
looking good?
after the etc comment is the old code
Oh okay. Yeah, seems fine. Keep in mind potential threading issues since you're using Runnable, I've slapped myself in the face over that more than once
I'm somewhat scared about that :/
Though a LOT of the old code upon receiving data would go to a runnable anyways since if I didnt I would get the error that stuff is getting instantiated without being in a "gdx context"
so it should be fine..?
Yeah it's fine, just something to keep in the back of your head.
yep
also I have to make a custom type of runnable since normal runnables dont take in parameter data and these need to
am i right or would that be a big no-no
(Just discovered "lambda expression" and wow! they look cool)
Yep, that lol
The run method intentionally doesn't have parameters, because it's starting a different thread. It doesn't make sense. But you do want data in that thread, so you'd extend Runnable with parameters in the constructor and make them member variables.
Runnables don't start threads, though
you can look at Consumer for a type that brings in a parameter and doesn't return anything
Is this fine..?
you lose a lot of type definition by it being varargs of just type Object
Maybe -- I'm not the best to jump in on that part of the conversation. If you can define your data with some structure -- say a parent class / base type -- that might help
I have to rethink this anyways since if I were to continue I'd run into problems
specifically JSON objects not being gwt-friendly
I've used GWT a long time ago, but not at all in this way so not sure there. Could you use a Map instead?
not sure
also, are you importing any library for the JSONObject ?
but I might just scrape the runnables and just define all the different callback setters inside the Socket implementation
that way it knows what to do by default
it's not like I'm making custom callbacks depending on conditions anyways
just "when you get this data, do these things to these variables"
yeah, I think more or less you're dealing with serialization/deserialization there, where you're losing type information as it's deserialized, so everything is a bunch of Objects
perhaps (big words 😵)
serialization = converting objects/data to bytes, and deserialization converts bytes back to objects
Well then I don't think that's true, since the novelty of Socket.IO is that instead of having to serialize everything some basic data types like String and JSONObject as directly sent and recieved
It's just that if I want to make a general "on" method work I need to allow for any type of data since the parameters to respond to certain callbacks may be different
more or less, that's what happens, though -- all the data that's deserialized is some type of Object, but you don't know what without looking at some other information
so you can write a generic event handler which takes the varargs Objects, but you won't know what those represent for sure
so then you'll need to look at some data to determine what type the Object(s) really are, and cast them
right, but I'm only handling a handful of events that I know 100% info about like what's sent and what happens when recieved
It might be worth your while to try to see if you can get a JSON library working with GWT, IMO. Then you can just pass in a JSON to Java directly and work from there.
but I see what you mean
I haven't had too much luck getting libraries to work in GWT 😦
This one seems pretty applicable I think: https://github.com/czyzby/gdx-lml/tree/master/websocket
ahh well, maybe not -- in their sample it says they use Vert.x for the server implementation of web sockets
I dont want to have to redo my server side code :/
well for the client side it might be okay then
Hmmm could be. I thought they just added some fallbacks like long-polling and other methods
i came up with I think the dumbest possible solution but itll work
without getting a JSON gwt to work, my only other option was to like, create a switch statement for the on method and do different code depending on the event id, and ALSO would require certain variable references to work
so fuck it, ill just let that class do all the work
now if I did get a JSON GWT lib to work I wouldnt have to do that but
hmm
Suggestion, get a proof of concept with your current method to make sure it will work (with GTW, Java, socket.io, etc., just at a basic level to make sure it doesn't not work), then you can put in the work to get a JSON library working to make your life easier.
Except you can only use that in your html module, your core module doesn't reference GWT. Unless you add it.
Oh
shoot I was already undoing code
How do I add it @pearl ore ?
just normal build.gradle stuff?
I think
oh thank god
i got scared
time to redo my undoing
trying to figure out how to write this stuff again...
nvm i dumb
I lost some cool information I was having before
now it's "get" and I have to cast to string :/
my eyes...
just finished the transition... i guess I can try actually running this now (on desktop) 😮
🤞
I got an answer from the server!... but it's still sending the data in the wrong form
Exception in thread "EventThread" java.lang.ClassCastException: class org.json.JSONObject cannot be cast to class com.google.gwt.json.client.JSONObject (org.json.JSONObject and com.google.gwt.json.client.JSONObject are in unnamed module of loader 'app')
... I hope making the server send GWT Json objects rather than regular Json objects isn't going to be horribly difficult
@pearl ore
What's your code on the client side from socket.io to Java?
Like your native function I guess
oh my god you're right
i am very tired, sorry
Oh god now I understand
what I will have to do to make this cross-compatible
between desktop and HTML
oh my god no
well its fine the desktop build is only for myself to test with anyways...
maybe if the game gets popular I'll release a desktop version and THEN the trouble will begin
for now I can keep being dumb about it right @pearl ore
Wait what?
I dont understand what you mean
You mean, what I would have to do if I wanted to be cross-compatible?
Yea
oh okay
yeah better not even think about it for now
Uh oh... I have bad news
``` still happens after I made sure that my GWT socket implementation used GWT Json
this is the method:
public void emit(String event, Object... args) {
try {
JSONObject data = new JSONObject();
for(int i = 0; i < args.length-1; i+=2){
data.put((String)args[i], (JSONValue)args[i+1]);
} socket.emit(event, data);
} catch (JSONException e) {
System.out.println("SOCKET.IO: Error sending data to server in \"" + event + "\" event.");
}
}```
the import is correct
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;```
maybe I should reload my project and it just didnt update
let see
This is from Java to JavaScript right?
You can't cast an Object to a JSONValue like that
I suppose, if you mean JS as in my server
Well, okay. That's actually not what's causing the exception.
I take it back lol, a bit tired
It might be an issue but better to tackle one thing at a time
For some reason it's using org.json.JSONObject instead of com.google.gwt.json.client.JSONObject
As far as I can tell
I think I know what happened!
So the first time I got the error, it's because I had sent the non-GWT friendly JSON data and expected to get GWT-friendly JSON data
I think that as a result of that, the connection with the server broke, the server didn't finish initializing me as a player, and thus the information that I disconnected wasn't sent after I left
Meaning that the server is still holding old data that is non-GWT friendly
so lets try restarting the server and see if that fixes it
does that sound possible @pearl ore ?
ok nevermind, i was wrong
non-GWT friendly? JSON is JSON
The only thing that matters is that it's going from JS --> Java and Java --> JS correctly
ah yeah makes sense, when it goes to the server it doesnt matter whether is gwt json or not
the server sees it all the same
so what could the problem be?
I don't think i'm sending normal json anywhere
I mean the exception is hinting at it
For some reason it's using org.json.JSONObject instead of com.google.gwt.json.client.JSONObject
As far as I can tell
right, but why?
could it be because my gwt socket io interface uses these?
import io.socket.client.Socket;```
AFAIK imports are transitive, see if there are imports in those classes that are messing with anything
I think the names I'm using might be confusing me
I'm calling the browser/other modules one "GWT socket interface" because socket.io doesn't work with GWT
and the HTML one "JSNI socket interface" because I'm using jsni (am I? i dont even know yet lol)
but that's dumb
ill just call them "Web" and "NonWeb"
I'm sorry, I checked all imports but I see no mention of org.json JSON objects 😐
@pearl ore 😰
i'm not using it, but......
Hmm
should I just grab the java library, replace all usages of JSON to gwt json ones, compile it back to a jar [THING I DONT KNOW HOW TO DO YET] and import that as a library?
Are you able to get rid of your try-catch statement and just let the exception happen? It'll help pinpoint exactly where it's happening
Or debug and step over and try to find it
What Java library?
yeah should I just make my own custom copy of it
I don't know how to turn it into a jar so I can import the library yet
What part of it sounds bad
should I just grab the java library, replace all usages of JSON to gwt json ones, compile it back to a jar
There's almost never a need to do that. The only time I've ever seen it done was to swap out XNA for MonoGame in Terraria.
What library are you referring to?
I'm guessing since they never intended for any of it to be GWT-compatible they didn't think to use GWT-compatible classes
So when my app recieves JSON data it will automatically assign it to a org.json JSON object
and after that from what I understand it's impossible to convert one into the other
currently I still haven't done the HTML implementation of my Socket interface, I'm still on the non-web one
which simply calls methods to the Java Socket.IO library that I already have
what I was proposing was to modify that library so that it transfers gwt JSON objects and not org.json ones
if you have a better solution of course i am all ears, im just making uneducated guesses
Ah, okay. So personally, I'd stick with org.json when you're using core. That way core doesn't need to reference GWT. You can convert from GWT's JSONObject to org.json's JSONObject in your implementation when going from JS --> Java and Java --> JS. Simplest way is to stringify the JSON and then have the other type decode it back.
Or you can do it from JavaScript. Instead of the native function returning JSONObject, return string and just do return object.stringify();. Then you can decode it into an org.json.JSONObject.
You mean, decode it into a gwt JSONObject? that sounds good
if thats what you mean
@pearl ore Is that what you mean or did you really mean decode it into a org.json JSONObject
So from Java --> JS, Java uses org.json.JSONObject. Inside your implementation in your html project, you can convert from org.json.JSONObject to a string (stringify the JSON object). When you call the JS native function pass a string instead of a JSON object (static native void js_Function(String jsonStr), for example). Then your JS function can parse it into a JSON object (let jsonObj = JSON.parse(jsonStr);) and send it off to socket.io.
From JS --> Java, have the function return a string (static native String js_Function(), for example) and your JS can stringify the JSON object before returning it (return JSON.stringify(jsonObj);). Then you can turn that string into an org.json.JSONObject and pass it back.
That way your core only uses org.json.JSONObject, which is what the Socket.IO library uses anyway.
Just to be 100% clear, when you say "Java --> JS" or back, you do not mean "Client --> Server" (server being in JS), right?
Nope
On your client, you have to call JavaScript at some point in order to use the JavaScript version of socket.io. That's what I'm referring to.
Alright
Currently reverting to using JSONObject so I can test for Desktop and be 100% that this can work, then we'll worry about JS
should be good soon
Great, the game totally works! 😄
for desktop
The interface only uses 3 methods
@pearl ore
I KNOW this is a dumb thing to ask
and you're probably facepalming
but uh how do I make it understand this is JS
(At least when I'm through with figuring this out I'll be able to release the basic LibGDX app working under this source.io framework for cross-compatibility so people won't have to go through the same struggle 😄 )
@pearl ore sorry for pinging (its getting very late)
ohhh
i was looking at how the library I linked yesterday was doing it and I didnt notice that
thanks
now I gotta figure out how to do the thing you said and I'm almost out of libgdx hell
while im figuring it out here's the start of the class and I'm certain I didn't do it right
as in there is nothing I've written that would point towards the JS library
and also I'm using the incompatible JSON objects but I know I have to change that
@pearl ore
are you here?
man we're getting close to getting this working, im happy