texts: LibGDX Lights and Shadows for my 2D TiledMap Game (like Terraria/Starbound)

texts:
Im currently working on my Terraria-Clone. After I have finished generating the world, I would like to add light and shadow to my game. For example, it would be light in the Upperworld during the day, but dark at night. In the Underworld (Mines/Caves) it is dark as well, but there are supposed to be blocks like torches, which radiate a light aura. At the moment I don't have anything yet, because I don't know how to start with this topic. That is why I am here now. Does anyone have any suggestions what I could do?
Here a Picture of my Game:

How I want it to look:

I hope you can help me.
Have a great day!


texts:
How can I move and rotate an object along with another using vector math?

This is using Godot 3.1 using a KinematicBody2D as a ship with a StaticBody2D as a planet.


texts:
How to fill region with repeated texture? Now I'm using next method:

spriteBatch.begin();

final int tWidth = texture.getWidth();
final int tHeight = texture.getHeight();

for (int i = 0; i < regionWidth / tWidth; i++) {
    for (int k = 0; k < regionHeight / tHeight; k++) {
        spriteBatch.draw(texture, i*tWidth, k);
    }
}

spriteBatch.end();

It's very obvious. Maybe is there any built in method?


texts: How to best select a texture pair to use in height blending when using a splatmap shader

texts:
In my project, I'm implementing a shader to combine up to 4 textures in a terrain using a splatmap texture (https://en.wikipedia.org/wiki/Texture_splatting).
I want to combine the splatmap blending with the height blending technique, described in: http://untitledgam.es/2017/01/height-blending-shader/. This technique basically defines a function to interpolate between two textures more realistically based on height information.
The problem is, in order to use height blending, I need to know which pair of textures I'll be interpolating, while in the splatmap I actually have four different texture sets (channels, R G B and A).
So what I want to achieve is a shader that will select the pair of textures for which the splatmap channel information is strongest, and interpolate between the two while discarding others. My "naïve" attempt was something along the lines of (simplified version, pseudo-code and only for illustrative purposes):
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D splat;

void fragment_shader() {
    sampler2D sampler;
    if (splat.r > splat.g) {
      sampler = tex1;
    } else {
      sampler = tex2;
    }
}

The problem, I realized, is that I can't store samplers inside a variable like this due to limitations in GLSL. So I'm looking for a soultion that would be similar to this. Particularly, I would want to avoid a solution where I'm sampling all four textures for every texture lookup. That is because I will be using some expensive techniques inside the shader which require several texture lookups, and I don't want to increase the computation cost 2x.
EDIT My current attempt to do this consists of computing two vectors to select the maximum and "second maximum" channels. A channel vector would be something like (1.0, 0.0, 0.0, 0.0) to indicate the red channel should be used. The implementation is currently looking something like this:
vec4 c1, c2;
  float m = max(max(max(splat_val.r, splat_val.g), splat_val.b), splat_val.a);
  if (m == 0.0) {
      c1 = vec4(0.0);
      c2 = vec4(0.0);
  } else {
      c1 = vec4(float(splat_val.x == m), float(splat_val.y == m), float(splat_val.z == m), float(splat_val.a == m));
      vec4 splat_val_2 = splat_val * (vec4(1.0) - c1);
      float m2 = max(max(max(splat_val_2.r, splat_val_2.g), splat_val_2.b), splat_val_2.a);
      c2 = vec4(float(splat_val_2.x == m2), float(splat_val_2.y == m2), float(splat_val_2.z == m2), float(splat_val_2.a == m2));
  }

Where c1 and c2 end up being the channel vectors for the largest and second largest splatmap channels. I'm still facing some issues when there are multiple elements with the same value though, and I keep thinking there should be a better way to do this.
After I compute the channel vectors, I'd still need a nasty static if structure like the following, so all in all I'm not sure my current attempted solution is a very good one:
if (dot(c1, red_constant) == 1.0) {
  if (dot c2, green_constant) == 1.0) {
    do_shader(tex_sampler_R, tex_sampler_G);
  }
  else if (dot c2, blue_constant) == 1.0) {
    do_shader(tex_sampler_R, tex_sampler_B);
  }
} else if (dot(c2, green_constant) == 1.0) {
  // ...
}
// ...


texts: Will a game made with .Net Desktop Development, be able to run on Windows' desktops?

texts:
I am new to making games (I have experience only with pygame), and I want to start creating with C#. I've found out that Monogame is a very good engine. On my way of setting up, in the part where I install Visual Studio, Monogame's site says:

Before installing Monogame, you'll need to install Visual Studio 2019 or later (any edition, including Community) with the following components, depending on your target platform:

.NET Core cross-platform development - For Desktop OpenGL and DirectX platforms
Mobile Development with .NET - For Android and iOS platforms
Universal Windows Platform development - For Windows 10 and Xbox UWP platforms
.Net Desktop Development - For Desktop OpenGL and DirectX platforms to target normal .NET Framework

I want to create a game to be played on desktops (most preferably, on Windows), and as it writes, Universal Windows seems the most suitable. Is there any difference, if I use .NET Desktop Development? I see that for other type of applications, this is very common.


texts: How can I make user-friendly polar coordinate movement around a circle?

texts:
I am working on a 2D game where you land on planets with a ship and can exit the ship and walk around.

These planets are very small (think ~350 pixel radius sometimes), and are seen from the side. So you can easily see the whole planet on the screen generally.

This may be sort of confusing so here's a picture:

I am using the A and D keys to move counter-clockwise and clockwise, respectively. The problem is that if you are on the "top" of the planet (upper half), this makes sense: A moves to the left, D moves to the right. However, if you are on the "bottom" of the planet (bottom half), A moves to the right, and D moves to the left.

Any ideas on how can I make this more user-friendly?


texts: Making a 2D sprite move in a curved jump in Unity

texts:
Given a 2D Sprite (I'm using NGUI if it matters), what is the simplest way to move it to another position using a curve that resembles a jump?

When I used cocos2d, there was an action called JumpTo which basically tweened the sprite to a particular position. It had parameters for curve height and speed and such.

How can I achieve this in Unity? I have the DOTween plugin if it helps (although I don't think it does this).

I don't have a predefined path for the sprite to follow either. I only want it to behave like cocos2d.


texts:
I read that most servers handle more than 50 requests per second. Is this true? how many requests can a normal server handle?

How do MMOG manage requests having to update player actions instantly?


texts: How can I develop Flash games without expensive software?

texts:
I've been playing with writing flash games in my spare time, but up to this point, I've just been using a trial version of Adobe Flash Professional. I'm aware of FlashDevelop, but their documentation is basically non-existent when it comes to the workflow of developing purely with FlashDevelop.

Does anyone know of any good tutorials for developing Flash games purely with FlashDevelop?

Alternatively, does anyone have any other free/cheap software recommendations to use in place of Flash Professional?


texts:
Working on a side scroller game in Unreal Engine 4 and I need to create a water cut off effect like seen in the screenshot of Ori and the Blind forest.

Basically need a side perspective on water bodies like lakes and ponds where I can see objects underwater as well as above water. Water may be subject to ripples and disturbances (caused by player or fish swimming in the water).

Thanks


texts:
Currently I am using scene2d and I want to implement shadows using Box2d light.
I want shadows under characters but when I draw something after render() , it draws nothing.
 For example, in draw() method of an actor,

    public void draw(Batch batch, float delta){
        super.draw(batch,delta);
        ray_handler.render();
        batch.draw(Something......)
    }

But when draw before render, it shows no problem.

    public void draw(Batch batch, float delta){
        super.draw(batch,delta);
        batch.draw(Something......)
        ray_handler.render();
    }

How can I solve this problem?


texts:
I'm currently building a shader that takes a 2D texture sampler and uses UV coordinates to map it. This works fine for all textured objects. However, I'm having a bit of a problem as I'm trying to render a Mesh with no texture and the shader objects just keeps sampling based on the parameters of the last object I rendered. What is a good way to make sure whenever no texture is available it will just treat it as a white texture or something?

One thing I've thought of was creating and binding a white 1x1 texture but that seems overkill.

Related question:
I've been wondering about this and I've yet to find an answer: Is it best to make a multi-purpose shader or constantly change the shader program for different objects in the same render update? For instance, should I have just created a shader for non-textured objects?


texts: Problem getting mouse events while keys held down in SDL2

texts:
I'm attempting to write input capturing code using SDL2 on Windows.  However, I'm running into a problem.

Whenever a key is held down, the SDL event queue has no mouse movement, nor will the mouse move on my screen. Instead, The SDL event queue continually returns the key I am holding down as an SDL_KEYDOWN event.

Here is a simple example program which reproduces the problem exactly:

#include <SDL2/SDL.h>
#include <iostream>

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_EVERYTHING);
  SDL_Window* window = SDL_CreateWindow("Moust Input Test", SDL_WINDOWPOS_UNDEFINED,
                                        SDL_WINDOWPOS_UNDEFINED, 640, 480,
                                        SDL_WINDOW_SHOWN);
  SDL_Event event;
  for(; ;) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        SDL_DestroyWindow(window);
        return 0;
      } else if (event.type == SDL_MOUSEMOTION) {
        int x, y;
        SDL_GetMouseState( &x, &y );
        std::cout << "Mouse moved to: " << x << " " << y << std::endl;
      } else if (event.type == SDL_KEYDOWN) {
        std::cout << "Code of key pressed: " << event.key.keysym.sym << std::endl;
      }
    }
  }
  return 0;
}

What I would expect to happen is that, when I hold down a key (for example, 'a'), it prints exactly once:

Code of key pressed: 97

And then, while they key is held down, if the mouse is moved, it prints every time the mouse is moved:

Mouse moved to: [wherever]

Instead, I'll keep seeing over and over again:

Code of key pressed: 97

And I will not get any mouse movement whatsoever on the screen, nor will I get my mouse movement log printed, until I release whatever keys I am holding down.

Anybody know how I can capture mouse movement while I have a key held down?

The only thing I can think of which could possibly be relevant is I am compiling with MinGW using:

g++ -Dmain=SDL_main test.cpp -o test.exe -L./lib/SDL2 -lmingw32 -lSDL2main -lSDL2 -mwindows -mconsole

Thanks.

Edit: I've also just noticed that the problem persists even when the window is minimized- if I am holding a key down in this text window while my program is minimized in another Window, the mouse stops working, though my program is not printing out the key code.


texts:
I'm trying to handle all the physics on the client and correct data on the server.

e.g.

Client_1 wants to move right
Server broadcasts that
Clients simulating Client_1's movement
Client_1 sends it's coordinates to the server (every 100ms)
Server validates coordinates based on client's last position and last update (which is stored on the server)
Server corrects Client_1's coordinates on every client

But when FPS<60 players are moving faster than they should, which causes server to teleport them back.

My question is basically how to check x,y without teleporting players with high latency (or low fps).

Server:

var now = Date.now();
var clientX = ...x position sent by client...
var clientY = ...y position sent by client...
var timeDiff = Math.ceil((now - player.lastPositionUpdate)/5)*5;
var timeDiff = timeDiff > 1000 ? 1000 : timeDiff;
var pixelPer100 = player.speed/10;
var maximumPixelDiff = (pixelPer100/100) * timeDiff;
player.lastPositionUpdate = now;

if (clientX > player.position.x){
    var diff = clientX - player.position.x;
    newX = player.position.x + (diff > maximumPixelDiff ? pixelPer100 : diff);
}
..and more

Client:

update: function(){
    player.body.velocity.x = player.speed;
    tick++;
    if (tick == 6){
        tick = 0;
        sendPositionToServer();
    }
}

I'm using Phaser with Arcade Physics.


texts: Can Google Translate's audio files be used in a game?

texts:
For my game, I need text-to-speech. Since it's Android, I decided to settle for MP3s, since the range of words spoken is few.

For my prototype, I'm using Google Translate to generate the audio since it has awesome pronounciation across multiple languages.

But can I use it in production? What if I sell my game for $1 on the app store?

All I can find on SE is that the API may be LGPL, and that the licensing page mentions the API is only available for academic research -- nothing more. My usage is a bit different; I'm actually capturing the audio bits and using those instead.

I'm curious to know the license for this; I can't find anything with my Google-fu.


texts: What are some common FOV for third person games?

texts:
I am trying to decide on a field of view (FOV) for a third person game and I really don't know where to start. It would be very helpful to have some points of reference from recent TPS games and the FOV they use by default. The trouble is many third person games (or at least those I have tried) do not have any settings or information about what their default FOV is. I have had a look at Uncharted 4, Hitman (2016), The Division and GTA 5 but cannot find information about their FOV anywhere.

I understand that each game is different and the type of gameplay will determine the FOV choice here, but it would be very useful for me to have some existing examples as a starting point. Is there any good place to find this out?


texts: Implementing my Entity System. Questions about some problems I have found

texts:
Well during this week I have deciding about implementation of my entity system. It is a big topic so it has been difficult to take one option from the whole. This has been my decision:

1) I don't have an entity class it is just an id.

2) I have systems that contain a list of components (the list is homegenous, I mean, RenderSystem will just have RenderComponents).

3) Compones will be just data.

4) There would be some kind of "entity prototypes" in a manager or something from we will create entity instances.Ideally they will define the type of components it has and initialization data.

5) Prototype code to create an entity (this is from the top of my head):

int id=World::getInstance()->createEntity("entity template");

6) This will notify all systems that a new entity has been created, and if the entity needs a component that the system handles it will add it to the entity.

Ok, this are the ideas. Let's see if some can help with the problems:

1) The main problem is this templates that are sent to the systems in creation process to populate the entity with needed components. What would you use, an OR(ed) int?, a list of strings?.

2) How to do initialization for components when the entity has been created? How to store this in the template? I have thought about having a function in the template that is virtual and after entity is created an populated, gets the components and sets initialization values.

3) Don't you think this is a lot of work for just an entity creation?.

Sorry for the long post, I have tried to expose my ideas and finding in order other could have a start beside exposing my problems.

Thanks in advance,
Notbad.


texts: Why Inverse Transform the Ray when doing Transformation?

texts:
I am adding 3D affine transformations to my ray tracer, and it seems all the literature on the web recommend inverse transforming the ray instead of transforming the 3D objects.

Why is that? There are a lot more rays than objects in a typical ray tracing scene, so wouldn't it be more efficient to transform the objects themselves?


texts: cocos2d-x Label Load Image like Sticker-Smile..(by html or …)

texts:
hi and sorry for my english...

i am using cocos2d-x (c++)... can i load sticker (smile) in my Label(a text mixed by image)? i know that we can load bitmap fonts by:

Label::createWithBMFont

also i know many frameworks like flash can load html texts by textbox which can contains img tags... but what is the best way for adding smile image in the text of label in cocos2d-x?? can cocos2d Label load html text like :

"hello
How Are You"???

thanks...


texts:
I'm trying to render depth texture in XNA 4.0. I'm read few different tutorials several times and realy cannot understand what I'm doing wrong.

Depth shader:

float4x4 WVPMatrix;

struct VertexShaderOutput
{
    float4 Position : position0;
    float Depth : texcoord0;
};

VertexShaderOutput VertexShader1(float4 pPosition : position0)
{
    VertexShaderOutput output;
    output.Position = mul(pPosition, WVPMatrix);
    output.Depth.x = 1 - (output.Position.z / output.Position.w);
    return output;
}

float4 PixelShader1(VertexShaderOutput pOutput) : color0
{
    return float4(pOutput.Depth.x, 0, 0, 1);
}

technique Technique1
{
    pass Pass1
    {
        AlphaBlendEnable = false;
        ZEnable = true;
        ZWriteEnable = true;

        VertexShader = compile vs_2_0 VertexShader1();
        PixelShader = compile ps_2_0 PixelShader1();
    }
}

Drawing:

this.depthRenderTarget = new RenderTarget2D(
    this.graphicsDevice,
    this.graphicsDevice.PresentationParameters.BackBufferWidth,
    this.graphicsDevice.PresentationParameters.BackBufferHeight);

...

public void Draw(GameTime pGameTime, Camera pCamera, Effect pDepthEffect, Effect pOpaqueEffect, Effect pNotOpaqueEffect)
{
    this.graphicsDevice.SetRenderTarget(this.depthRenderTarget);
    this.graphicsDevice.Clear(Color.CornflowerBlue);
    this.DrawChunksDepth(pGameTime, pCamera, pDepthEffect);

    this.graphicsDevice.SetRenderTarget(null);
    this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, null, null);
    this.spriteBatch.Draw(this.depthRenderTarget, Vector2.Zero, Color.White);
    this.spriteBatch.End();
}

private void DrawChunksDepth(GameTime pGameTime, Camera pCamera, Effect pDepthEffect)
{
    // ...

    this.graphicsDevice.RasterizerState = RasterizerState.CullClockwise;
    this.graphicsDevice.DepthStencilState = DepthStencilState.Default;

    // draw mesh with pDepthEffect
}

Result:

As I see output.Position.z always equals output.Position.w, but why?


texts: How can I make my tank move smoothly and not jump from 0 km/h to 10 km/h?

texts:
I'm building a multiplayer game of tanks in node js. at the moment I have the movement smooth and mastered but my problem is that at them moment it's basically just unrealistic.

The tanks starts at 0 km/h but upon pressing w/Arrow up key it goes straight to 10 km/h, as you can imagine with any vehicle that's just unrealistic to do.

I want to know how to make that speed up happen without it being too bulky or confusing. I'm a beginner programmer so I'm not too informed in the world of programming. Can somebody help me with this?

I figured it would have to do with an acceleration command but I have no idea how to do that either.


texts:
How do game engines efficiently handle and draw pixels within a given display?

As a personal project / exercise, I had begun developing a simple game engine written in Java, but came across the issue of figuring a way to efficiently and quickly update the pixels within the game window.

Since I had decided to model this engine after the NES' (which maintains a resolution of 256x240 at 60hz, if i recall correctly) 6502 chip, I had quickly created an array of pixels at that resolution.

Though already thinking that looping through the array and drawing the pixels within that loop was not the best way to handle this task, it performed worse that what I had thought.

My method was only able to produce 100 frames a second at 30% CPU usage, and 40% GPU.

How did the early programmers of the NES / 6502 chip accomplish this task of drawing the display, given the limited power of systems back then, or is this really the most efficient method of going about this problem?


texts:
I am looking for a way to select tiles within a bounding box for object placement within a scene/world, similar to Roller Coaster Tycoon and other simulation games.

(source: tumblr.com)

In the above screenshot of Theme Parkitect you can see that a 4x4 grid is used as the footprint for the object being placed. Given the bounding box and location of the mouse, how can I suitably determine the neighbouring tiles which fall into the bounding box?

I have implemented a graph like structure of tiles, corners and edges by following Amit's fantastic articles on Red Blob Games. As of such, I have a graph of all  tiles and their neighbours as well as associated tile edges and corners. These tiles are laid out diagonally against the world axis so simply selecting all tiles within a rectangular region isn't as simple (or maybe it is?) as i'd expected. This layout can be changed if necessary however.

The main source of information used to steer my implementation has been from Amit's Thoughts on Grids and the graph structure implemented in his article about Procedural Map Generation

As a bonus, I would like to implement a way to rotate the object being placed such that a footprint of 1x5 could be rotated to instead be 5x1. I would imagine that once the basics of multiple tile picking has been implemented this should be reasonably simple.

Unfortunately, Amit's articles don't seem to cover this topic and the approaches I have found and tried so far haven't quite yielded the correct results. Any help that fits in with the graph like structure for connected tiles, edges and corners would be greatly appreciated.

I have tried to implement the approach outlined in Raytracing on a Grid with a mixture of both Broad-Phase collision and A* Path Finding but neither of these two approaches cover selection of multiple surrounding tiles.

I am not concerned with the viability of tiles for placing objects at this point (i.e.: sloped edges of tiles or obstructions from other objects). The ideal solution for now would simply be to find the tiles included within the bounds.

My initial forays into this have resulted in incorrect results whereby the bounding rect doesn't include all neighbouring tiles (sometimes missing entire rows/columns) or returning neighbours outside of the bounds. I was pretty sure that I was close to a winning implementation but my vector math isn't strong enough to validate my findings.


texts:
I am trying to make a top down view game in java using the Slick2d library, for lighting I wanted to do something like this : http://www.redblobgames.com/articles/visibility/.
I was wondering if there was a way to tint or light places on the screen in Slick. I would have my map rendering in the background and a lightmap in front.

Solution :
https://github.com/ariejan/slick2d/blob/master/src/org/newdawn/slick/tests/AlphaMapTest.java


texts: Returning The Position Of A Sprite Drawn & Updated By A List

texts:
My problem is this, when iceBoy hits any of the newGrounds in the ground.groundAmmount list, it will return the specific position of this newGround so that i can set iceBoy's position based on the newGround that he touched. Here is the code that i have for this:

foreach (Ground newGround in ground.groundAmmount)
{
      if (HitGround())
      {
           iceBoy.position.Y = newGround.position.Y;
      }
}

but like Byte56 this will only loop through all of the newGrounds in the list and then iceBoy.position.Y will only equal the last newGround added to the list. how could i create another method that will have a return value of the position of the exact newGround that iceBoy is touching?


texts: Spatial Partitioning - How do I find the object is in the tree?

texts:
I understand the structure of Spatial Partitioning Trees - BSP, Quad and Octal. You just take a space and split it into however many parts specified by your tree - BSP:2, Quad:4, Octal:8. I've written a self managing quad-tree (in Java but this shouldn't matter) before, and I had the same question I'm having now (in XNA).

How, once an object is in the tree, do I find it specifically. ie. I put the player in the tree, he updates ever frame, but unlike the other AI driven/world objects, he needs input, and his health needs to be checked every frame to see if the game is over. How do I get him out, without knowing his exact location.

My solution last time was to just leave the player out of the tree, and when I need to do collision checking, just pass in his coordinates to get the possible collisions, but I feel like this isn't using the tree the way it's supposed to be used.

Right now I'm trying to write a tree for a 3D game this time in XNA. So my second question really is which tree is better? I've heard BSP trees are the standard, but weren't oct trees written for dividing 3D spaces (Same as quad trees are for 2D)?


texts: Google's ForPlay library, where does it fall down?

texts:
ForPlay is lauded as a pretty amazing accomplishment by Google's own. But I'm holding off on making any solid judgements as yet...

I'm wondering if anyone has used this and has found any major flaws? I'd like to know what these are. Considering that the code is written in Java and is compiled for Flash, Android and HTML5 additionally, I'm wondering how it performs on those platforms as compared with games written natively for those platforms -- if anyone has done any comparisons in this regard.

For those who are unaware of what ForPlay (now renamed PlayN) is, see the repository and this video.


texts:
So I posted not too long ago looking for an alternative system to what I'm using for game metrics, meaning information I post each update when something specific happens (enemy damaged, killed, a wave starts, player taking damage, etc). I got suggestions to implement something more similar to "events" instead, where I could have a general interface to define events and create derivative classes to represent specific cases. This would be fine, but I'm having a hard time figuring out how to define achievements now in terms of these new events.

My current system, I have long values for each type of metric: player, enemy, kill, damage, damage types, weapons, and various other pieces of information. Each value is a single bit and I compose them together so I can later check specific bits to see if a certain metric was posted and apply it to my achievement progress tracker.

For example, let's say ENEMY = 1, DAMAGE = 2, PISTOL = 4. I compose these together to indicate that an enemy was damaged by the pistol this update and the resultant value is 7. I can later look at the individual bits for different cases. Say I have a general achievement for tracking number of kills regardless of enemy type, I could extract the bit relevant to KILL and ENEMY and see if one of those was posted, and if so, increment the milestone. However, I can also use this same metric to apply to an achievement that's tracking kill counts for specific enemies if I wanted to.

I also have more complicated achievements that use a rudimentary state machine with logic deciding what each state does with the metrics that are posted and determine the next state.

The reason this was problematic is because even though this system is great and works well, it means I only have 64 values I can use to compose together, and with the number of weapons and enemies I'm adding, I'm going to run out fairly quickly.

When I tried implementing "metric events" instead, I found that defining milestone achievements (and likely state machine achievements) was impossible because I could only take the metric events with all the information composing that class, and couldn't "compose" them together and then pick them apart. It also made it a lot more difficult to figure out how to save that information to a file for keeping track of achievements in save files.

Does anyone have a suggestion as to how I could approach this? If it helps, you can find my current implementation of my achievement system here:

Achievements System

You can also find the AchievementController class under the controllers package one level up. This controller defines the achievements themselves, if you want to take a look at how I define my achievements.

I really appreciate any insight people may have. Links to articles detailing how to properly implement an achievement and metrics system would be very helpful, or if anyone has their own examples of systems they've implemented, that would be awesome.


texts: physics.addBody() with custom shapes in Corona SDK

texts: Does the physics.addBody() only work with Circles and Rectangles? Or is it possible to physics.addBody() on vector shapes or sprites or with masks or something?


texts: 2d Scale width and height based on distance

texts:
I'm drawing a health bar on top of each player. I transform 3d position to 2d. I would like to draw it smaller when distance increases. Any simple math for that? Let's say bar width is 30 and height is 10 it looks good only on distance == 100. What formula should I use to make it decrease in size when distance increases?

Should resolution of the game be taken into consideration?


texts:
I've been trying to program a game for the past while and I can't ever figure out one thing: collision detection. I can get up+down and left+right to work, but when I put them together, they interfere with each other.

I seriously don't really know how to do it, and I don't want to have to use Box2D or any other premade collision detection system. All I need is something simple and will work in 4 directions.

Here's the code I have now from my Player class:

for (int i = 0; i < blocks.size(); i++) {
            Block b = blocks.get(i);

            if (isCollidingDown(b)) {
                b.doTopCollision(this);
            }

            else if (isCollidingUp(b)) {
                b.doBottomCollision(this);
            }

            else if (isCollidingLeft(b)) {
                b.doRightCollision(this);
            }

            else if (isCollidingRight(b)) {
                b.doLeftCollision(this);
            }

        }

Here's the actual detection code. I know it's long, but just roll with it:

public boolean isCollidingDown(Block b) {
        if ((Float.compare(this.yPos,b.yPos+b.height) <= 0) && (Float.compare(this.yPos,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)>=0)) {

            if (((Float.compare(this.xPos, b.xPos)>=0) && (Float.compare(this.xPos, b.xPos+b.width)<= 0)) ||
                    ((Float.compare(this.xPos+this.width,b.xPos)>=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0))) {

                    return true;

            }
        }
        return false;
    }

    public boolean isCollidingUp(Block b) {
        if ((Float.compare(this.yPos+this.height,b.yPos) >=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0) && (Float.compare(this.yPos,b.yPos)<=0)) {

            if (((Float.compare(this.xPos, b.xPos)>=0) && (Float.compare(this.xPos, b.xPos+b.width)<= 0)) ||
                    ((Float.compare(this.xPos+this.width,b.xPos)>=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0))) {

                return true;
            }
        }
        return false;
    }

    public boolean isCollidingLeft(Block b) {
        if ((Float.compare(this.xPos,b.xPos+b.width) <=0) && (Float.compare(this.xPos,b.xPos)>=0)) {

            if (((Float.compare(this.yPos, b.yPos)>=0) && (Float.compare(this.yPos, b.yPos+b.height)<=0)) ||
                    ((Float.compare(this.yPos+this.height,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0))) {

                return true;
            }
        }
        return false;
    }

    public boolean isCollidingRight(Block b) {
        if ((Float.compare(this.xPos+this.width,b.xPos) >=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0)) {

            if (((Float.compare(this.yPos, b.yPos)>=0) && (Float.compare(this.yPos, b.yPos+b.height)<= 0)) ||
                    ((Float.compare(this.yPos+this.height,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0))) {

                return true;
            }
        }
        return false;
    }

Note that I had to do this Float.compare() thing because floats aren't accurate when comparing. Also, I'm not using Java2D, I'm using a framework called libgdx. That shouldn't matter though.

What can I do? Thanks!

EDIT: Guys, that's not the point. I know my code is very unprofessional, but the point is that the collisions don't work the way they're supposed to. I just need a 4-way collision system with boxes. That's all.


texts:
some times it takes time to create the sprite structures in the scene, I might need to setup structures inside this sprite to meet requirement, thus I would hope to reuse such structures with the game again and again.

I tried that, remove the child from parent, detach it from parent , clean parent with the sprite. but when I try to add the sprite to another scene, it's just wont pass the assertion that the sprite already have parent

did I miss some step ?

add an example:

I have a sprite A which involves of quite a few steps to construct, so I used it in scene A layer A, and then I want to use it in scene A layer B, scene B layer A1  etc..... generally speaking I don't want to reconstruct the sprte again.


texts:
I'm learning SDL 2.0 at the moment and I've seen this method for loading BMPs:

SDL_Texture* LoadImage(std::string file)
{
    SDL_Surface *loadedImage = nullptr;
    SDL_Texture *texture = nullptr;
    loadedImage = SDL_LoadBMP(file.c_str());

    if (loadedImage != nullptr)
    {
        texture = SDL_CreateTextureFromSurface(renderer, loadedImage);
        SDL_FreeSurface(loadedImage);
    }
    else
        std::cout << SDL_GetError() << std::endl;
        return texture;
}

How could I switch it up to load PNG files?

EDIT: Woops, forgot to add my method of loading PNGs.

SDL_Texture* grass_image = nullptr;
grass_image = IMG_LoadTexture(renderer, "res/grass.bmp");
SDL_Rect grass_rect;
    grass_rect.x = 0;
    grass_rect.y = 0;
    grass_rect.w = SCREEN_WIDTH;
    grass_rect.h = SCREEN_HEIGHT;

if (grass_image == NULL)
    std::cout << "Couldn't load grass_image" << std::endl;

while (!quit && mainEvent -> type != SDL_Quit)
{
    SDL_RenderCopy(renderer, grass_image, NULL, &grass_rect);
}

I just don't want to have to do that for EVERY image.  So how could I put that into a function?

Thanks!


texts:
The project I'm building for test purposes is working fine but I have dependencies flying around everywhere due to the XNA framework.

My issue is in the content.load textures/sounds/fonts.
I have them as public variables (i.e.
Texture1 = Content.load(of texture2d)("Texture1") )

I'm passing a 'Game1' pointer into the constructor of every new class being instantiated to gain access to these variables.

Am I missing an OOP trick that would prevent me having to pass a pointer to 'game1' to every New class?


texts: Are there tools available for building hierarchical sprite-based objects in games like Vector Man or Gunstar Heroes?

texts:
Possible Duplicate:
  Tools for 2D skeletal animation

I'm looking for a tool that would let me build multi-part sprite objects of the kind you can find in Sega Genesis games like Vector Man and bosses like Gunstar Heroes. Not only are they built with multiple sprites, but they're animated on a kind of really basic skeletal model.

Are there any tools out there that builds that sort of thing?


texts: how to get surface direction of object in hit point in unity

texts:
I'm simulating shooting by raycasting. I want to instantiate a bullet hole or mark on the spot where a bullet hits an object. But the surface of the object at that point may have different angle or direction:

How can I find the object's surface direction to make the right transform for a bullet hole?


texts:
I am creating this little 3d space shooter and am somewhat unsure on how to implement the laser beams.

I'm thinking about something along Star Wars and the like where mostly you shoot rather short laser beams but very many of those.

Should I create a "tube" for each of the beams, render them via instancing and give them a better look just with the shader?

How would you go on about this? I was rather perplexed that there was no good tutorial on this matter out there.


texts: How to implement character sprite effects like in TowerFall?

texts:
In TowerFall, the character sprites seem to dynamical stretch and compress with player action.

Should I do this at the sprite sheet level? Should the sprites do this, or is there a better way to do this?

How would you achieve this in Unity?


texts: Heightmap based Tilemap (like found in OpenTTD or SimCity 2000/3000)

texts:
I have a little pet project I have been working on the past few weeks. I am trying to create procedurally generated isometric maps with elevation. Like in OpenTTD or the classic SimCity games). I realize that OpenTTD is open-source but I am not very fluent in C++ and need to code this project in Unity (C#)

I have thought of different ways of going about it and done some research but don't know where to start. I thought about using marching cubes to generate a grid of points and then figure out the tile based on the four points.
Any suggestions/pointers?


texts: OpenGL ES Single Bitplane Texture (or something close)

texts:
I'm looking to use a texture to store single bits (or a low number of bits, two or three). This in of itself isn't hard if you're using nearest neighbor sampling with some bit plane unpacking. The kicker here is I need the values to abide to bilinear interpolation (or something that looks like interpolation), and manually emulating bilinear interpolation is rather slow and potentially prone to problems due to hardware differences.

This is an instance where I'm going to have a lot of similarly-sized textures. The best thing I've come up with is using a 4 x 4-bit channel texture and storing a texture in each channel. This isn't exactly great for texture cache, but it's near native-hardware supported. Unfortunately, this also requires four times the space (4 bits instead of 1 bit per texel) assuming the number of textures I have to store is divisible by 4.

Is there a better way to store 1 bit per texel? Or even 2 bits per texel?


texts: Matrix loading problems with jbullet and lwjgl

texts:
The following code does not load the matrix correctly from jbullet.

//box is a RigidBody
Transform trans = new Transform();
trans = box.getMotionState().getWorldTransform(trans);
float[] matrix = new float[16];
trans.getOpenGLMatrix(matrix);
// pass that matrix to OpenGL and render the cube
FloatBuffer buffer = ByteBuffer.allocateDirect(4*16).asFloatBuffer().put(matrix);
buffer.rewind();
glPushMatrix();
glMultMatrix(buffer);
glBegin(GL_POINTS);
glVertex3f(0,0,0);
glEnd();
glPopMatrix();

the jbullet is configured as so:

CollisionConfiguration = new DefaultCollisionConfiguration();
dispatcher = new CollisionDispatcher(collisionConfiguration);
Vector3f worldAabbMin = new Vector3f(-10000,-10000,-10000);
Vector3f worldAabbMax = new Vector3f(10000,10000,10000);
AxisSweep3 overlappingPairCache = new AxisSweep3(worldAabbMin, worldAabbMax);
SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver();

dynamicWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
dynamicWorld.setGravity(new Vector3f(0,-10,0));
dynamicWorld.getDispatchInfo().allowedCcdPenetration = 0f;
CollisionShape groundShape = new BoxShape(new Vector3f(1000.f, 50.f, 1000.f));
Transform groundTransform = new Transform();
groundTransform.setIdentity();
groundTransform.origin.set(new Vector3f(0.f, -60.f, 0.f));
float mass = 0f;
Vector3f localInertia = new Vector3f(0, 0, 0);
DefaultMotionState myMotionState = new DefaultMotionState(groundTransform);
RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, groundShape, localInertia);
RigidBody body = new RigidBody(rbInfo);
dynamicWorld.addRigidBody(body);
dynamicWorld.clearForces();

Nothing is rendered on the screen. What am I doing wrong?


texts:
I recently bought a new laptop, with Intel i5-5200U HD graphics 5500 and AMD Radeon R5 M230 2GB and 8gb ram, and heres what happens with my Unity: If open it, minimize it and then maximize again, it'll render some weird black screen in random areas of the editor, like this:

But, if I instead of minimizing unity and just opened other window , when I go back to unity nothing happens, no black weird "squares". So this just happens when I minimize unity itself and then maximize it, if I maximize another program over unity and then open unity again, it will not happen. Can anyone please tell me why this happens??? I always have to restart unity.... Is this a problem with my video card? plz help


texts: Creating a voxel world with 3D arrays using threads

texts:
I am making a voxel game (a bit like Minecraft) in C++(11), and I've come across an issue with creating a world efficiently.

In my program, I have a World class, which holds a 3D array of Region class pointers. When I initialize the world, I give it a width, height, and depth so it knows how large of a world to create. Each Region is split up into a 32x32x32 area of blocks, so as you may guess, it takes a while to initialize the world once the world gets to be above 8x4x8 Regions. In order to alleviate this issue, I thought that using threads to generate different levels of the world concurrently would make it go faster.

Having not used threads much before this, and being still relatively new to C++, I'm not entirely sure how to go about implementing one thread per level (level being a xz plane with a height of 1), when there is a variable number of levels.

I tried this:

for(int i = 0; i < height; i++)
{
    std::thread th(std::bind(&World::load, this, width, height, depth));
    th.join();
}

Where load() just loads all Regions at height "height". But that executes the threads one at a time (which makes sense, looking back), and that of course takes as long as generating all Regions in one loop.

I then tried:

std::thread t1(std::bind(&World::load, this, w, h1, h2 - 1, d));
std::thread t2(std::bind(&World::load, this, w, h2, h3 - 1, d));
std::thread t3(std::bind(&World::load, this, w, h3, h4 - 1, d));
std::thread t4(std::bind(&World::load, this, w, h4, h - 1, d));

t1.join();
t2.join();
t3.join();
t4.join();

This works in that the world loads about 3-3.5 times faster, but this forces the height to be a multiple of 4, and it also gives the same exact VAO object to every single Region, which need individual VAOs in order to render properly. The VAO of each Region is set in the constructor, so I'm assuming that somehow the VAO number is not thread safe or something (again, unfamiliar with threads).

So basically, my question is two one-part:

How to I implement a variable number of threads that all execute at the same time, and force the main thread to wait for them using join() without stopping the other threads?
How do I make the VAO objects thread safe, so when a bunch of Regions are being created at the same time across multiple threads, they don't all get the exact same VAO? Turns out it has to do with GL contexts not working across multiple threads. I moved the VAO/VBO creation back to the main thread. Fixed!

Here is the code for block.h/.cpp, region.h/.cpp, and CVBObject.h/.cpp which controls VBOs and VAOs, in case you need it.

If you need to see anything else just ask.

EDIT: Also, I'd prefer not to have answers that are like "you should have used boost". I'm trying to do this without boost to get used to threads before moving onto other libraries.


texts: How do I pass an object location into a vertex shader?

texts:
I am using Blender Game Engine. I want to create a large flat plane, and deform it locally near a moving object.

So far (despite being a beginner at shaders) I've written a vertex shader for the plane which moves the vertices to their correct positions (constant positions, for now).

I cannot find a way to swap that constant location with an object's location updated every frame, while the shader is running. I am not even sure if it's possible. I only want to access a specific object's center from the shader.


texts:
I start learning unity recently and I am using Unity 2017.3.0f3. Now I'm creating a Block Breaker game and I tried to create a way to check win condition and to go to next level.
So I write those two variables:

public static int BreakableCount = 0;
public int RemindBricks = 0;

At start I write this code to count the number of blocks in my scene:

 isBreakable = (this.tag == "Breakable");
     if (isBreakable) {
         BreakableCount++;
     }

Which works perfectly and after that I set the win condition:

void OnCollisionEnter2D (Collision2D col)
     {
         Handlehits ();
         print ("bricks count is= " + BreakableCount);
         print ("remind brick is= " + RemindBricks);
         print ("_______________");
         if (RemindBricks == BreakableCount) {
         SimulateWin();
         }
     }
     void Handlehits ()
     {
         int MaxHit = hitsprites.Length + 1;
         TimeHit++;
         if (TimeHit >= MaxHit) {
             RemindBricks++;
             DestroyObject (gameObject);

   } else {
     LoadSprite();
     }
 }

My problem is RemindBricks only increased once and after that it won't increase at all. Here is the result:

And here my entire project to download if you want. So please tell me why my variable won't increase and how to fix it. Thanks.


texts: How do I destroy a class/how do I link a class to a gameObject

texts:
I am fairly new to programming and I decided to create a Pong game. I created the sprites and was able to make the paddles and the dot work. The only help I needed was when I wanted the dot to recognize where it was hit.

Now I wanted to respawn the dot when it hits an wall behind the racket. I created an transparent sprite with a 2D Collider. Now I wanted to use this:

If dot hits LeftWall destroy gameobject dot

But when I use:

 if (col.gameObject.name == "WandLinks")
    {
      Destroy(Dot.gameObject);
    }

it tells me "Dot" is a class and can't be destroyed. This I understand. But why does the rest work? And how do I create a reference from the class to a new gameObject? Thank you very much.

(My next solution is to place the code for the destruction inside my wall but that's not my desired solution)

-
This is my whole code for the dot

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Dot : MonoBehaviour

{
public float speed = 5;
public Transform spawnPoint;

void Start()
{
    // Initial Velocity
    GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
}

float hitFactor(Vector2 ballPos, Vector2 racketPos,
                float PaddleRight)
{
    // ascii art:
    // ||  1 <- at the top of the racket
    // ||
    // ||  0 <- at the middle of the racket
    // ||
    // || -1 <- at the bottom of the racket
    return (ballPos.y - racketPos.y) / PaddleRight;
}
public void RespawnDot()
{
    Instantiate(dot, spawnPoint.position, spawnPoint.rotation);
}

void OnCollisionEnter2D(Collision2D col)
{
    // Note: 'col' holds the collision information. If the
    // Ball collided with a racket, then:
    //   col.gameObject is the racket
    //   col.transform.position is the racket's position
    //   col.collider is the racket's collider

    // Hit the left Racket?
    if (col.gameObject.name == "PaddleLeft")
    {
        // Calculate hit Factor
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    // Hit the right Racket?
    if (col.gameObject.name == "PaddleRight")
    {
        // Calculate hit Factor
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(-1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    if (col.gameObject.name == "WandRechts")
    {
        RespawnDot();
    }

    if (col.gameObject.name == "WandLinks")
    {

    }
}
}


texts:
So I published an app about 3 weeks ago and it still says 10 downloads, but I have google analytics in the app and it says my app has nearly 1000 downloads. After 2 days my app said 10 downloads and it has never updated since then.

Has this ever happened to any of you? I have heard of a few days to a week of delay but 3 weeks is ridiculous. It should have updated by now.


texts: Collision Detection Code Structure with Sloped Tiles

texts:
Im making a 2D tile based game with slopes, and I need help on the collision detection. This question is not about determining the vertical position of the player given the horizontal position when on a slope, but rather the structure of the code.

Here is my pseudocode for the collision detection:

void Player::handleTileCollisions()
    {
        int left = //find tile that's left of player
        int right = //find tile that's right of player
        int top = //find tile that's above player
        int bottom = //find tile that's below player

        for(int x = left; x <= right; x++)
        {
            for(int y = top; y <= bottom; y++)
            {
                switch(getTileType(x, y))
                {
                    case 1: //solid tile
                    {
                        //resolve collisions
                        break;
                    }
                    case 2: //sloped tile
                    {
                        //resolve collisions
                        break;
                    }
                    default: //air tile or whatever else
                        break;
                }
            }
        }
    }

When the player is on a sloped tile, he is actually inside the tile itself horizontally, that way the player doesn't look like he is floating. This creates a problem because when there is a sloped tile next to a solid square tile, the player can't move passed it because this algorithm resolves any collisions with the solid tile. Here is a gif showing this problem:

So what is a good way to structure my code so that when the player is inside a sloped tile, solid tiles get ignored?


texts: Advance efficient water physics simulation

texts:
Summary: I am looking at creating a large(ish) ocean which multiple ships will be present in doing their own thing. I want the ocean to be a life like as possible but without compromising too much on rendering speeds.

A Little more detail: I am using Unity to create the game in and ultimately I will need to be able to release the game as a web player to there lies my limitations of the water simulation.
For the actual simulation of the ocean I will need it to be able to react to the ships movement and vice-versa. The end product of the simulation I want to be able to look like this simulation of a ship in water (if possible) to be done efficiently. http://youtu.be/H4ACKAUU3O0?t=3m51s

I have started reading up on other information and looked at the other similar questions to mine:
1) Water/Ocean simulation and physics
  - I have read this question fully, am looking at not using wind as said in this question but will use this as a reference when creating the final product. (I would like to add to the information from that question with the answers on this question.)

2) Resources of realistic water simulation?
  - I have started going through the tutorials that the answer linked to and so far they seem good but do not look like they will answer my question.

The water will have splashes in reaction to the objects in the water (particle effects I believe) and small waves will come off the objects in the water e.g. ripples. Also if you are a smart cookie that wants to be awesome you should include in your answer about putting a shader on the water.

Also since the ships will be moving all at independent speeds and traveling through the sea, for efficiency I don't want to just make the water massive so is there a way to only render/simulate the water within a certain radius from each of the ships?

What I am looking for in an answer:

I would like to know the what tricks for making this type of simulation light-weight can be used for these types of water simulations and specifically in unity.
What limitations will I encounter when creating this and why they are limitations
The basic work flow of creating something like this step by step. (e.g. step 1: to make the object that will be in the water)
Are there any open source projects for these types of simulations?


texts: Unity scene performance - better to use one scene and toggle what is active?

texts:
Unity scene performance questions

In Unity, were one to have a scene that is basically identical in all but a few ways, would it be better to keep them as separate scenes, or to have them be one scene and have a script run during init to make all the modifications? Such as change the ground material from green to white to make it snowy, and such?

If you went the separate scene route, would that drastically bloat the project? would all things be stored twice?


texts:
I'm faced with the following problem:

I'm trying to implement a rigidbody-based movement for my submarine game which means I want (need?) to useAddForce() and AddTorque() in order to get proper collision detection.

Currently I'm achieving the desired rotational behavior by quaternion multiplication/rotation.

But with this approach, the submarine bugs through the terrain. To avoid that it seems my only option is to use a rigidbody.

Here's a video illustrating the problem.

On the left is the correct behavior. I want to keep the nose pointing where it has been tilted at and not rotate around a fixed axis, Vector3.up in this case.

How can I calculate the correct input for AddTorque(vec3) to get the result I need?

Left attempt with quaternions (what I need):

input2 = Input.GetAxis("Sideways");
transform.rotation =
    Quaternion.Euler(0, input2 * Time.deltaTime * rotation_speed, 0) * transform.rotation;

Right attempt with torque (which doesn't quite work yet):

// in Update()
rotateY = Input.GetAxis("Sideways");

void FixedUpdate() {
    // experimenting with AddTorque() and various inputs didn't
    // get me any further
    rb.AddRelativeTorque(Vector3.up * rotateY * speed);
}

I hope someone can point me in the right direction, thanks in advance.


texts: glColor3f() 0.0 = no intensity 5.0 = full intensity?

texts:
I have a very weird behavior of openGL's glColor right now.

I've wasted hours to detect why my line colors acting so weird until I found out that 0.0 rgb values is zero intensity and 5.0 lead to full intensity (yes NOT 1.0 it's not clamping!)

If I color a line with 1.0, 1.0 1.0 I get very dark grey instead of white.
If I color a line with 5.0, 5.0 5.0 I get white.
Here is my code:

gl.glDisable(GL2.GL_BLEND);
gl.glDisable(GL2.GL_TEXTURE_2D);

/* We need to disable any shaders to get colored lines */
gl.glUseProgramObjectARB(0);

gl.glColorMaterial(GL2.GL_FRONT_AND_BACK, GL2.GL_AMBIENT_AND_DIFFUSE );
gl.glEnable(GL2.GL_COLOR_MATERIAL);

gl.glBegin(GL2.GL_LINES);
for (int lineIndex = 0; lineIndex < lineSegments.getNumberOfLines(); lineIndex++) {
  gl.glColor3d(5, 0, 0);
  //gl.glColor3dv(lineSegments.getLineColor(lineIndex).data(), 0);
  gl.glVertex3fv(lineSegments.getLineStartPoint(lineIndex).floatData(), 0);
  gl.glVertex3fv(lineSegments.getLineEndPoint(lineIndex).floatData(), 0);
}
gl.glEnd();

gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glEnable(GL2.GL_BLEND);

Why is OpenGL acting so weird on glColor? Did I miss a gl state or something?
I could scale up the colors so I bypass this, but I want to find out whats wrong here.

(The code example leads to a line that ist 100% red)


texts: Monobehaviour script method does not appear as an option for UI button's On Click

texts:
I have the following script, and when I try to use a UI button to call the CheckGuess method,  it does not appear as an option:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Guessthenumbergame: MonoBehaviour
{
    public InputField input;

    public Text infoText;

    private int guessNumber;

    private int userGuess;

    // Start is called before the first frame update
    void Start()
    {
        guessNumber = Random.Range(0, 100);

    }

    // Update is called once per frame
    public void CheckGuess()
    {
        userGuess = int.Parse(input.text);
        if (userGuess == guessNumber)
        {
            infoText.text = "You guessed the number right";
        }else if (userGuess > guessNumber)
        {
            infoText.text = "Your number is higher";
        }else if (userGuess < guessNumber)
        {
            infoText.text = "Your number is lower";
        }
        input.text = "";
    }
}


texts: TiledMap blocks makes Animation invisible

texts:
//////////////////////////////////////////////////////////////////////////////////

Got it fixed. Thanks to anyone who tried to help me.
New Code:

mapManager.render();
spriteBatchForeground.setProjectionMatrix(Main.getGraphicsManager().getAdvCamera().getCamera().combined);
spriteBatchForeground.begin();
    worldManager.render(delta, spriteBatchForeground);
    animationManager.render(spriteBatchForeground);
    particleEffectManager.render(delta, spriteBatchForeground);
spriteBatchForeground.end();

/////////////////////////////////////////////////////////////////////////////////

I just implemented my animations but now I discovered a problem with my TiledMap.

Here some Screenshots:

Code for 1

spriteBatchForeground.begin();
// mapManager.render();

spriteBatchForeground.setProjectionMatrix(
    Main.getGraphicsManager().getAdvCamera().getCamera().combined );
worldManager.render(delta, spriteBatchForeground);
animationManager.render(spriteBatchForeground);
particleEffectManager.render(delta, spriteBatchForeground);
spriteBatchForeground.end();

Code for 2

spriteBatchForeground.begin();
mapManager.render();

spriteBatchForeground.setProjectionMatrix(
    Main.getGraphicsManager().getAdvCamera().getCamera().combined );
worldManager.render(delta, spriteBatchForeground);
animationManager.render(spriteBatchForeground);
particleEffectManager.render(delta, spriteBatchForeground);
spriteBatchForeground.end();

Issue:

The animation isn't drawing when I enable the drawing for the tiledmap.
I have no idea why this happens...


texts:
The only way to load an asset from an asset bundle into memory is to load the entire thing, decompress and pull out the asset you want, then unload the entire thing, except the assets you want. This seems impractical for sharing assets between bundles. For example, if asset bundle A wants a single asset from asset bundle B, it must load all of B, pull out the asset, then destroy B. The alternative to this is to extract the shared assets and create a new bundle call asset bundle C. The problem with this is that B must have been designed this way before being built, which it won't be if it was built before A (it has to be since A depends on B).

Using the resources folder results in a huge blob of bytes that, from what I understand, cannot be changed after build, and is certainly not differ able for patches.

Putting the pros of asset bundles and the resource folder together, I figure that having an asset bundle for every asset is the best of both worlds. Is there problems with this? Is my understanding of asset bundles or the resource folder flawed?


texts: TVOS SiriRemote micro pad value change handler is not called

texts:
I have a UIViewController which inherits from GCEventViewController and I register a value change handler for the GCController microPad Profile.

But when I use the SiriRemote in the Simulator none of my handling methods is called. When I stop with the touches the touchesEnded function is called though on that particular view controller.

This is are excerpts of my code:

var gameController : GCController? {
    get {
        return self.currentGameController
    }
    set(v) {
        self.currentGameController = v
        self.controllerUserInteractionEnabled = false
        if let microPad = v!.microGamepad {
            microPad.allowsRotation = false
            microPad.reportsAbsoluteDpadValues = true
            microPad.valueChangedHandler = self.microPadValueChangeHandler
        }

    }
}
...
 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    log.info("||||| TOUCHES ENDED IN GAMEVIEW_CONTROLLER |||||.")
}

func microPadValueChangeHandler( _ gp : GCMicroGamepad , _ gc : GCControllerElement ) {
    log.info("||||||||| microPadValueChangeHandler ||||||")
    log.info("|||||||||||||||||||||||||||||||||||||||||||")
    log.info("")
}

...

Any ideas why the microPadValueChangeHandler is NOT called and the touchedEnded is called?

Any help is greatly appreciated.

Cheers,

Frank


texts: How to create a very specific kind of joint in Farseer?

texts:
Edit

Problem solved (see Drackir's answer). Here's a demo of what I was trying to achieve with this joint. More info about the scenario on this other question.

Problem

I'm trying to create a very specific type of joint in Farseer that behaves like this:

Objects should always keep the same distance between them in both the X and Y axes.
Translation - A collision with one of the objects should move the entire group together, but the group must not rotate - only the individual objects may rotate around their centers as a result of torque.
Rotation - Objects should always have the same rotation. A collision with one of the objects should make all others rotate the exact same amount.

Here's a picture:

If there's no way to achieve this with Farseer out of the box, how would I go about extending it to create a new type of join that works like this? Basically I want every body to behave like a "clone" of the others, but with a fixed offset between them.


texts: Generate random point inside Perlin noise?

texts:
I’m working on terrain generation for a game of mine and has run into a slight problem. The terrain itself within the game procedurally generates as your character moves around. This means that all the world generation needs to somehow be based off of the position a certain tile—or region (chunk)—has in the world.

The world generation is rock solid so far and looks quite gorgeous! But I require one more component to make it complete—I need to somehow retrieve a random point within a piece of Perlin noise.

Let’s assume we had something like this:

int scale = 100;
float noise = perlinNoise.noise3(x / scale, y / scale, z / scale)

if(noise > .2f)
    setPixel(x, y, 0xffffff);

We’re drawing the result to the screen in form of pixels to try and see what happens. This way, we achieve regularly spaced out areas of noise. Now, what I would like to do is randomly generate one point located somewhere within a chunk of noise following the above “schematic”.

The above might look something along the lines of this:

xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxoooxxxxx
xxxxoooooxxxx
xxxxxoopooxxx
xxxooooooxxxx
xxxxxoooxxxxx
xxxxxxxxxxxxx

Where the x’s are what is not affected by the perlin noise in the above code example and o’s are affected—the o’s are plotted out on the screen by it—they’re the white pixels in the above example.

The little p as opposed to from the o’s and x’s, is the random point I’d like to have randomized inside every chunk of randomized Perlin noise, without having to pre-generate the world.

Is there a way in which this can be achieved? I’ve wrapped my mind inside out thinking of potential solutions—I’ve searched the web, but as though in vain. There appears to be nothing written on the subject.


texts: Create a instance of a C++ class within a blueprint

texts:
I'd like to create an instance of a C++ class in a blueprint.
That's my current approach, but the instance is None. Why?


texts:
I want to change the position of the Buttons inside a table, I tried setting their X and Y, or get their position when adding the Buttons on the Table, but it didn't work. It always aligns the button on the center.

Code:

    TextureAtlas ta = new TextureAtlas("Comecar.txt");
    final TextureAtlas.AtlasRegion as = ta.findRegion("comeca");
    final TextureAtlas.AtlasRegion as2 = ta.findRegion("comecaversao2");
    myTexRegionDrawable2 = new TextureRegionDrawable(as2);
    myTexRegionDrawable = new TextureRegionDrawable(as);
    myTexRegionDrawable.setMinHeight(300);
    myTexRegionDrawable.setMinWidth(260);
    myTexRegionDrawable2.setMinHeight(300);
    myTexRegionDrawable2.setMinWidth(260);
    b = new ImageButton(myTexRegionDrawable);
    op = new ImageButton(myTexRegionDrawable2);
    op.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
        }
    });
    b.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            gdxGame.setScreen(new Janela2(gdxGame));
        }
    });
    t = new Table();
    t.add(b);//I tried setting the position here
    t.add(op);
    t.setFillParent(true);
    stage.addActor(t);
    Gdx.input.setInputProcessor(stage);
}


texts: Get Cartesian coordinates from isometric coordinates

texts:
Coordenadas: X:140 Y:279
Coor Isometricas:128/69
X: 2  Y: 1.
CoordenadasConversas: 69:214.

CoordenadasConversas should be equal to Coordenadas.

CoordenadasConversas does not work.
The function I use is CoordenadaAIsometrico() - see below.

I applied the formula to convert from isometric to Cartesian, but it does not seem to work.

float cartesianX = (2.0f * isometricY + isometricX) * 0.5f;
float cartesianY = (2.0f * isometricY - isometricX) * 0.5f;

function Isometrico(){

    ctx.save();

    ctx.translate(0, 300);

    ctx.scale(1, 0.5);

    var radianes=-45 * Math.PI /180;

    ctx.rotate(radianes);
}

function CorIsometrico(xI,yI){

    yI=yI-300;

    yI=yI*2;
    var angle = ((-45 * Math.PI /180) * -1)
    var x2 = xI;

    var y2 = yI;
    var cos = Math.cos(angle);
    var sin = Math.sin(angle);

    var xI2 = Math.floor(x2 * cos - y2 * sin);
    var yI2 = Math.floor(x2 * sin + y2 * cos);

    console.log("Coor Isometricas:" + xI2  + "/"+  + yI2 );

    CoordenadaAIsometrico(xI2,yI2);
}

function CoordenadaAIsometrico(Xc,Yc){

    var Xcc = (2 * Yc + Xc) * 0.5;

    var Ycc = (2 * Yc - Xc) * 0.5;

    //Xc=Xc-50;
    //Yc=Yc+300;

    console.log("CoordenadasConversas: " + Xcc + ":" +  Ycc);
}


texts: Can Unity censor my content or invalidate my license for offensive content?

texts:
If I make an offensive game can they pull my license and prevent me from selling my game? Like we're talking think of the most offensive thing you can think of: you're in charge of the most efficient genocide against some specific racial/religious/political group, your choice... now imagine the game is mocking victims and generally being extremely rude, violent, and insensitive.

Now I have no intention of making such a horrible game but I am using an extreme example to ask my question. It's not unheard of for less extreme things to get blocked by brands who didn't want to associate with them, for example I saw that Apple removed the Confederate flags from Civil War games in the App Store.

Would Unity be able to prevent me from using their game engine or selling my game after I had already purchased appropriate Unity licenses and completed the game?

Do they have that kind of power with their licensing model? Or would even the most extreme cases still be legally allowed to sell the content?

I want to make something that may have some mildly provocative/divisive content (not as offensive as say, South Park, which I know was made in Unity, but more serious than South Park) and I'm just making sure I don't get a bunch of work done and then get disappointed later, wishing I had gone with some kind of more free/open engine.


texts: My money will only save for one game run

texts:
I am trying to make a money system my problem is that the money value only saves for 1 game run then the value returns to 0.
Here is my code. What should I do.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Money : variables {

    public Text cash;

    // Use this for initialization
    void Start () {

        if (counter < 9 && counter > 1)
        {
            money = money + 2;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 10 && counter < 20)
        {
            money = money + 5;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }

        else if (counter > 21 && counter < 30)
        {
            money = money + 15;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 31 && counter < 40)
        {
            money = money + 25;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 41 && counter < 70)
        {
            money = money + 50;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 71 && counter < 100)
        {
            money = money + 75;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 101 && counter < 200)
        {
            money = money + 100;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 201)
        {
            money = money + 150;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);

        }

        cash.text = "Credits: " + PlayerPrefs.GetInt("money", money);
    }
}


texts: Should the bullet trajectory calculated by server or by client?

texts: In a FPS game like Battlefield or Arma, when playing online, should the bullet trajectory be calculated by the server or by the client?


texts: Libgdx RotateToAction does not directly rotate between 179 and -179

texts:
It took me a bit of debugging to realize why I'm having trouble with my rotations and it seems that rather than just moving the 2 degrees between 179 and -179, it prefers to rotate all the way in the other direction, the full 358 degrees.

Is there any way to make it go the short way in this case?

Code I have so far:

public void rotateTo(float targetRotation)
    {
        RotateToAction rotateToAction = new RotateToAction();
        rotateToAction.setRotation(targetRotation);
        rotateToAction.setDuration(2f);
        if(Math.abs(this.getRotation()-targetRotation) > 180)
        {
        /*failed attempt to force rotation*/
            SequenceAction sequenceAction = new SequenceAction();
            RotateToAction rotateToAction2 = new RotateToAction();
            rotateToAction2.setRotation(180);
            rotateToAction2.setDuration(1f);
            sequenceAction.addAction(rotateToAction2);
             sequenceAction.addAction(rotateToAction);
            this.addAction(sequenceAction);
        }
        else
        {
            this.addAction(rotateToAction);
        }
}


texts: How to copy the value of a variable from one script to another in Unity?

texts:
I would need some help with making two floats from two different classes, match their "data".

What I want to do here is to make it so when Body.healthb hits a value of 0, Head.health will also hit 0.

Any suggestions? I'm barely new to this.

The class from which the float comes from:

public class Body : MonoBehaviour
{
  public GameObject body;

  public float healthb = 50f;

  public void TakeDamageb(float amountb)
  {
    healthb -= amountb;
    if (healthb <= 0f)
    {
      Dieb ();
    }
  }

  // Update is called once per frame
  public void Dieb()
  {
    Destroy (gameObject);
  }
}

The class it has to reach:

public class Head : MonoBehaviour
{
  public static float health = 10f;
  public void TakeDamage(float amount)
  {

    health -= amount;
    if (health <= 0f)
    {
      Die ();
    }
  }

  // Update is called once per frame
  public void Die()
  {
    Destroy (gameObject);
  }
}


texts: Is there a maximum delay an UDP packet can have?

texts:
I am currently implementing a real-time network protocol for a multiplayer game using UDP. I am not having any technical difficulties, but as I always have to care about late UDP packets I am wondering just how late they can arrive.

I have researched the topic and have not found any mention of it, so I assume there is no technical limitation, but I wonder if common network/internet architecture (or hardware) gives an effective limitation of how late a UDP packet can be delivered.


texts: how to detect if an object is hit by a certain raycast in it's own code

texts: I have been working on a sandbox game in Unity, and I am wanting to use a raycast on the cursor, but I am needing for the blocks themmselves to detect whether the cursor's raycast is hitting. I am needing the code in javaScript. Thanks in advance!!!


texts: Anchor a health bar to a character/enemy

texts:
I have a game I'm working on where the player can see the health bars of the player's avatar and other creatures in the game.  I want this health bar to always follow the character/creature around.  However, I can't figure out how to do this.  I thought having the position change when the respective object moved would do the trick, but apparently, it doesn't.  When watching the health bar's transform, however, it shows that it is moving with it's respective object but I don't see it on the game screen.  Can anyone explain how I go about accomplishing this?  Here's the Dropbox link to the project.

HealthBar Script

public class EnemyHealthBar:MonoBehaviour{
    public Texture2D healthBar;
    public Texture2D health;
    public Rect healthBarPosition;
    public Rect healthPosition;
    public GameObject monster;

    void Start(){
    }
    void Update(){
        transform.position = new Vector3(monster.transform.position.x, monster.transform.position.y, monster.transform.position.z);
        Debug.Log(transform.position);
    }
    void OnGUI(){
        GUI.DrawTexture(healthBarPosition, healthBar);
    }
}

Video of what's currently happening

Dropbox Link


texts: Best way to get the maximum moveable Area

texts:
I was thinking about creating a polygonal area, for a given unit, in which it can move with a given range (radius) but with care for obstacles.

Here is a picture to visualize my idea:

My Ideas so far...

The Pathfinding Way

Create a Circle around 'unit' with given 'radius'
Check for intersections with obstacles
If an intersection is found, create a Path from 'unit' to intersectionPoint, but with pathLength == 'radius'
connect all endPoints to get the maximum moveable area
But what if no intersection is found because the obstacle is fully into the circle?

The Ray Way

Cast #Rays into all directions (e.g. 8 Rays for N, NE, E, SE, S, SW, W, NW) from 'unit'
Check for intersections between each Ray and the obstacles
If an intersectionPoint is found, create a Path from 'unit' to rayEndPoint with pathLength == 'radius'
connect all endPoints to get the maximum moveable area
But this needs more than 8 rays to be accurate enough and this will take calculation time

Have you got an idea on how to do this the best way?
Thanks in advance - LuaNoob

Edit #1:

The Flood Fill Way

Read something about flood filling algorithm. I guess this will be the best thing to try.

Example for maximum moveable range = 4

'X' = unit
'#' = wall

# # # # #

3 3 3 3 # 4

2 2 2 # 3 4

1 1 1 2 3 4

1 X 1 # # 4

1 1 1 #

# # #

Edit #2:

Current attempt: Custom Visibility Graph (not tried yet)

I now got i to work to create fast and accurate visible Areas.
What im gonna to do next is:

try to find the first point on the obstacle, that is in a line of sight by 'unit' and the not reachable endPoint of the Visibility-Ray-Cast
create a new Visibility Graph from there but with 'newRadius' = 'radius' - distance(unit, firstPointOnObstacle)
connect the Points
repeat it for every not reachable Point with custom 'newradius'
One Problem left: Holes cant be created, but these are the rarest occuring situations, where i can fit with


texts: How to place an object at the mouse position?

texts:
How can I place a object to position where I clicked in just x,y axis not in z,
I am trying to achieve it with

Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
object.transform.position = new Vector3(mousepos,mousepos);

but it does not seem to work, in fact the object doesn't even move.


texts:
I'm new to game programming and currently trying to understand Entity Component System design by implementing simple 2d game. By ECS I mean design, described here for example

In my game I have different kind of weapons: automatic, gun, grenade, etc...
Each type of weapon has it's own affect area (gun shots along the straight line and grenade explodes and covers some spherical area) , damage impact, visual effect and bullet amount, delay between shots. So I don't completely understand how to implement weapons. Should weapon be an Entity or it should be a component? And how the player should pick up a weapon, switch between different types of weapons and etc.


texts:
Hi recently i am trying to implement z ordering system into my directx framework.
So every object will have z order property(int), and this value will have higher priority than depth checking for rendering.
the current idea is from these three my assumptions that

depth check happens after vertex shader
value of SV_POSITION is used for depth checking
modifying z component of the value of SV_POSITION doesn't affect anything except in depth checking, because it is in projection space.

so after calculating projection position(local pos * WVP mat), i did projective dividision(it seems to make problem) and modified only z component corresponding orders that i want to draw with.

This is brief Vertex shader code

VS_OUTPUT output;

output.pos = mul(WVPMat, input.pos); // projection pos
output.pos /= output.pos.w;
output.pos.z -= renderPriority;

return output;

And !!! it kinds of works !!! but when i get my camera closer to any object,
it weird thing happens

it doesn't make any this weird thing unless projective division.
i am just curious why it happens instead of knowing another alternative way for z ordering.
but any further advices and informations would be really appreciated.


texts: Determining if a character is within the field of view in XNA

texts:
I'm trying to creating a field of view for the camera I'm making for a game. It rotates around a circle for 180 degrees while the head moves accordingly. I'm going to bound the field of view within an isosceles triangle using the method described on this website.

The problem I'm having is that I don't know how I'm going to detect if the field of view has intersected with the character as seen in this link.

Any help with this would be greatly appreciated.

[EDIT]

sorry I meant an asset in game representing a camera much like the enemy in the second link, not an actual camera class in XNA(really sorry)


texts: What should the data structure of a flexible ability system look like?

texts:
Hi guys I am currently working on a turn-based RPG that will require me to create numerous abilities with little overlap. I've been looking to other games to see how their ability and combat system is design and has run into issues regarding the data structure.

For the purpose of this question let's look at Pokemon RED & BLUE's ability system. Here are a few things that abilities can do:

Target User or Target Enemy or Both (i.e. Self Destruct)
Has an Accuracy Value
Has 1-2 Element value
Has PP Value
Is either a Special or Normal attack type (determines which stat is used to calculate the damage value.)
Increase / Decrease a primary Stat for the battle (ATK, DEF, SATK, SDEF, SPD, LUK)
Increase / Decrease overall Accuracy of the target by X% for Y turns (or the entire combat.)
Increase / Decrease overall Evasion of the target by X% for Y turns (or the entire combat.)
Deal Damage to Target for X amount (Where X can be based on calculated from the ability's base damage value, or using the damage taken that turn i.e. Counter)
Heal the Target for X amount (Where X can be based on calculated from the ability's base power OR based on damage dealt by the ability, i.e. Absorb)
Skips X Turn (i.e. Dig)
Critical chance * X for this attack.
Has X% chance to apply Status Effect Y (Y being: Burn, Confuse, Sleep, Poison, etc)
1 Hit KO Target
Cannot be hit for X turn (i.e. Dig)
Hits X times (Taking the ability's Accuracy value into account each time.)
Forces the attack to happen first
Forces the attack to happen last

I believe there may be many more. Now, Pokemon abilities can manifest a combination of any number of the above properties, usually no more than 3-4. For example:
- Counter = Skip 1 turn and deals damage to the enemy equal to 2x the damage received that turn as long as it's a Normal or Fighting move.
- Dig = Skip 1 turn, cannot be attacked that turn, deal damage next turn.
- Absorb = Deals damage, at the same time heal the user for 1/2 the damage dealt.
- Self Destruct = Kills self and deal huge damage to the enemy.
- Comet Punch = Hits the enemy 2-5 times (each time the hit chance is 85%)

As you can see, this gets quite complex. The examples cited above are just a few of the abilities that the game have and with those capabilities, it's possible to create quite a varied set of abilities that do not overlap.

The problem I am facing is 2 folds:

How would I design the data structure that would allow me to keep adding new abilities like this into the Database after the system has already been written?
How would the combat system actually handle the data once it's pulled out?

I assume that it will have to involve some form of scripting... and unstructured data structure like NoSQL so some abilities can have some things and some do not (like skipping turns.) However, how is this normally done? Do I store each ability as a blob somehow and handle them differently in code? That also means that the code MUST be able to handle ALL possible combinations (which will make the combat system extremely complex and time consuming to build?) Or did Pokemon just hard coded all the abilities (which seems quite impractical?)

Here's what we currently have for our ability data structure: (in JSON)

{
    "name"     : "Ability Name",
    "accuracy" : 0.85,
    "base"     : 50,
    "type"     : 0,              // (0 = normal, 1 = special)
    "target"   : 0,              // (0 = self, 1 = enemy, 2 = both)
    "PP"       : 30,
    "element1" : 1,              // (0 - 16, for each element)
    "element2" : 2,
    "blob"     : { ... }
}

This will allow for something like the above, but the code would still have to handle all the possible combination of the blob. Would my understanding be correct here?

Any insight would be extremely appreciated.

P.S. - If this question need to be reworded somehow to make it clearer, please let me know... it's an extremely complex problem so I did as best I could, but would appreciate feedback. Thanks!


texts: Why does my shader's Texture become unselected when I run my game?

texts:
I'd like to add a custom material to a line that I'm drawing in Unity (using Vectrosity).  I'm using Unity's built-in "Unlit/Texture" shader.  When I drag a texture from my Resources directory into the "Texture" slot in my shader, everything looks good:

But when I click play, the texture disappears:

and my line doesn't show up in my game.  However, if I drag the texture to the shader's texture slot after I click play, the texture seems to "stick" and my line renders as expected:

But once I stop and start the game, the texture again disappears.

Why is Unity kicking out my texture when my game starts?  Is there something wrong with my texture?  I don't see any warnings or errors in the console.  I've tried with numerous different textures, and they all do the same thing.

I'm using Unity 5.6.1f1.


texts: Remove a body when touched in LibGDX(Box2D)

texts:
I am using LibGDX to create a new project.

What i am trying to do is, i load bodies from a tmx file into levels which works fine. The bodies also has a sprite with them.

The problem is, is i would like to allow the user to touch certain bodies on the scene. When they touch the body they will be able to delete or remove it from the scene.

Is there anyway i can do this in LibGDX?


texts:
I'm writing a Forge mod for Minecraft 1.8. When I'm pressing the 'z' key a 3x3 Crafting grid should open. In the KeyInputHandler I call

@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
    if(KeyBindings.hackInv.isPressed())
    {
        EntityPlayer player = Minecraft.getMinecraft().thePlayer;
        World world = player.getEntityWorld();
        BlockPos pos = player.getPosition();
        player.openGui(CobaltCraft.instance, 0,world, (int) player.posX,(int) player.posY,(int) player.posZ);
    }
}

The code for the GuiHandler is:

@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
    if(KeyBindings.hackInv.isPressed())
    {
        EntityPlayer player = Minecraft.getMinecraft().thePlayer;
        World world = player.getEntityWorld();
        BlockPos pos = player.getPosition();
        player.openGui(CobaltCraft.instance, 0,world, (int) player.posX,(int) player.posY,(int) player.posZ);
    }
}

Ingame the Gui shows up when I press 'z'. But the Items glitch around. I have trouble picking them up (by left clicking) and sometimes the items just change places. And if I right click with the crafted item on a block it vanishes.
Please help me I don't know what to do,
Nova


texts: Unity - Check if sprite is within range around player

texts:
I need to know if a sprite is within range (circle or square doesn't matter) around the player. If the sprite is, let's say, 100 blocks away from the player, I will disable it. This wouldn't be too much of an issue, just compare positions and you're done. However, my game is a tile based game and I want the world to be as big as possible, which will result in millions of sprites.

I could also add a overlapcicle2D, but the problem is this these objects can't have a collider, since they could be walkable.

So how can I check if the millions of sprites are in range of the player, without lowering performance?

Alternatively, I could add occlusion culling. But how do you do this with sprites?


texts: C++ : Library for creating 3d view picture

texts:
I've got a numerical simulation, where I have as an output 3d matrix of billion elements - the visualisation of data is 2d flat image:

When I was starting I was just outputting 2d data to gnuplot, now I generate png file in program itself (to cut generation time). I would like now to get a 3d picture (in flat png) from my billion elements 3d matrix - in isotropic view etc. I found on the Internet things like ImLib3d for image processing, but I am afraid it's not what I am looking for.


texts: How does one go about building Alien Swarm?

texts:
Valve just released Alien Swarm on steam, along with all the source code. I would love to build a version of it on my own machine and play a little bit with the code.

Has anyone here tried to build it yet? Is it easy enough to just build and run it?

Thanks.


texts: C# Unity3D FPS apply damage to an enemy (Weapon bullet)

texts:
I am kindly new to Unity3d and c# and I don't understand how I could let a bullet deal damage to an other object. I've seen a lot of JS tutorials but no for C#. I've tried to use them, but it wont work. My code I've tried: For the Bullet (Prefab)

   using UnityEngine;
using System.Collections;

public class MoveBullet : MonoBehaviour {

    public float speed = 10.0F;
    public float damage = 10.0f;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        transform.Translate (0, 0, speed);

    }

    void OnCollisionEnter(Collision col){

        col.gameObject.BroadcastMessage("ApplyDamage", damage);

    }
}

And the one for the Enemy:

public class enemyhealth : MonoBehaviour {

  public int health = 100;

  // Use this for initialization
  void Start () {
  }
  // Update is called once per frame
  void Update () {
  }

  void OnDamage(){
    health--;
    if (health <= 0) {
      Destroy(gameObject);
    }
  }
}

What's not clear to me as well is, what type of Collider I should use (Box Collider, CapsuleCollider...) Or doesn't it makes a difference?

As I understood, Rigidbody is used for an other "technique" to make damage, am I right?


texts: GO Game, placing stones on grid intersections

texts:
I'm currently making a GO game and I am stuck on the most basic functionality. That functionality is being able to click on the intersections of the grid and ONLY the intersections to place a stone, either can be black or white. I have made a 2D array to represent the board but what I don't really understand is:

How do I draw the stones on the grid?
How do I reference the GUI grid to the 2D array?


texts: I want to know how I can make this game object follow the specified path in unity


texts: Is there a way to get the disassembly that your driver generates when compiling a shader? I noticed that you can get an accidental disassembly dump if you go over the maximum thread group size supported by the hardware in compute shaders, so naturally I figured there must be some way to do this for all shader types. Is there a reliable way to get the disassembly (perhaps specific to NVIDIA/AMD/Intel hardware), using tools or even just "hacks" like causing errors during compilation / linking?


texts:
Regarding Unity 2018.x:

The Facebook SDK provides a way to get log-in information from a user's FB account, and allows information or an image from an app to be shared TO Facebook. Is it possible to link / access / reference or in any  other way make use of a specific image on Facebook within my Unity app?

Ideally, I would like to be able to access the image upon target recognition and, even better, store the image for subsequent display within the app. Finally, even more ideally ideally, this would not be the FB profile picture.

All suggestions and links welcome.


texts:
I'm making a simple game, and have decided to try to implement a messaging system.

The system basically looks like this:

Entity generates message -> message is posted to global message queue -> messageManager notifies every object of the new message through onMessageReceived(Message msg) -> if object wants, it acts on the message.

The way I'm making message objects is like this:

//base message class, never actually instantiated
abstract class Message{
  Entity sender;
}

PlayerDiedMessage extends Message{
  int livesLeft;
}

Now my SoundManagerEntity can do something like this in its onMessageReceived() method

public void messageReceived(Message msg){
  if(msg instanceof PlayerDiedMessage){
     PlayerDiedMessage diedMessage = (PlayerDiedMessage) msg;
     if(diedMessage.livesLeft == 0)
       playSound(SOUND_DEATH);
  }
}

The pros to this approach:

Very simple and easy to implement
The message can contain as much as information as you want, because you can just create a new Message subclass that has whatever info necessary.

The cons:

I can't figure out how I can recycle Message objects to a object pool, unless I have a different pool for each subclass of Message. So I have lots and lots of object creation/memory allocation over time.
Can't send a message to a specific recipient, but I haven't needed that yet in my game so I don't mind it too much.

What am I missing here? There must be a better implementation or some idea that I'm missing.


texts: Rotating player around planet causes drift in gun aiming at mouse

texts:
I have a bug with the rotation of a gun object that follows the mouse position. It has issues when the parent object player rotates. Example:

The player has a gravity script to keep them aligned with the 'planet' as you walk around it. The gun is a child of the player, and it's supposed to always rotate to point at where the mouse is (sorry you can't see it in the gif). The gun normally flips itself at 90 and -90 (top and bottom), and flips the player to face the same side the mouse is on.
The problem is that the player rotates to stay aligned with the planet, but the 90 and -90 angles that the gun uses to decide whether to flip itself and the player of course don't rotate.
Here's my code for the gun:
  Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
  difference.Normalize();
  float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

  float startRotation = rotationZ + offset;

  float shotRotation = startRotation + Random.Range(-scatter, scatter);

  transform.rotation = Quaternion.Euler(0f, 0f, startRotation);

  //Flip the gun at top and bottom
  if (rotationZ < -90 || rotationZ > 90)
  {
      if (player.transform.eulerAngles.y == 0)
      {
          transform.localRotation = Quaternion.Euler(180, 0, -rotationZ + offset);
      }
      else if (player.transform.eulerAngles.y == 180)
      {
          transform.localRotation = Quaternion.Euler(180, 180, -rotationZ + offset);
      }
  }

  //Use gun rotation to set player direction
  //left
  if (rotationZ >= -90f || rotationZ <= 90f)
  {
      animator.SetFloat("Vertical", 0);
      animator.SetFloat("Horizontal", -1);
  }
  //right
  if (rotationZ <= -90f || rotationZ >= 90f)
  {
      animator.SetFloat("Vertical", 0);
      animator.SetFloat("Horizontal", 1);
  }


texts: How to get plausible platformer physics with Farseer on MonoGame/XNA?

texts:
I am creating a 2D Vectorial (made of polygons, not tiles !) platformer using MonoGame and Farseer Physics Engine. Everything works perfectly, except the movement of the character which doesn't feels right for a platformer, because Farseer is a physics engine...
I would like to have any advice to achieve a natural feeling -like Mario-. I didn't choose to make my own system because I'm simply not good enough to do something like this.

I've seen some questions already about it, but none had useful answers (they said like 'You have to do a lot of tweaking', but how do I do that exactly ?)

I could eventually use another engine that works for collision detection/response and that gives me more control over the player/entities, but i didn't find any yet. If you know any solution that's simple to use and that corresponds to what I need, then i'd love to hear it :)

Thank you for any help.

PS: Also, I am soon going to try to create AIs for my game. How would I make them move with great control (like the player) ?