texts: Follow behavior with randomization factor

texts:
I'm trying to make enemy follow player as in picture below, the code below is code for following player with steering behavior ( i'm not sure it steering works tho but it does follow player ), how would i code something like in the picture below to make the following more randomized but still going in direction of where player is.

Vector2f velocity,steering,desiredVel;
velocity = new Vector2f(player.getX() - getX(), player.getY() - getY());
velocity.normalise();
velocity.scale( maxVelocity);

// unsure what to do with random numbers yet
Random rand = new Random();
int randy = (rand.nextInt(101) -50);
int randx = (rand.nextInt(101)-50);

desiredVel = new Vector2f(player.getX() - getX() +randx, player.getY() - getY() +randy);
desiredVel.normalise();
desiredVel.scale( maxVelocity);

steering = desiredVel.sub(velocity);

steering = truncate(steering,maxForce);

steering.scale(1 / mass);

velocity = truncate(velocity.add(steering) ,maxSpeed);
this.velocity = velocity;

position.add(velocity);


texts: Why is Minecraft's default resolution (seemingly) non-standard?

texts:
Background: I'm writing some articles on Minecraft in an attempt to introduce 10-year olds to development through modding. I know very little about the game itself, though :)

I'm trying to understand why Minecraft appears to run in an "odd" default resolution. Grabbing a screenshot, I think it's rendering at 550x310 but that doesn't seem to match any of the "common" aspect ratios (although it's close to 16:9), nor is it evenly divisible by 16, which appears to be what the texture packs use.

Is it actually running at 550x310 in its default windowed mode? If not, what is the resolution?
Depending on the answer to the first question, why isn't it using one of the standard aspect ratios? I'm not familiar with OpenGL programming either so perhaps there is a common resolution close to what I'm guessing at that would make perfect sense.


texts: How to load a simple minimap, and hide the background?

texts:
I developed a small and simple 3D games minecraft style. I would add a "MiniMap". Until here everything is fine. I had the idea to load the entire map in the background, and then I added the edge of the minimap over. So I can move the map when the player moves. My problem is that I do not know how to make hidden anything above the minimap.
Have you any idea?

I'm stuck in my development

Here is a schematic of what I would do with my minimap. And hide all that is striped in red, outside the minimap.

Thank a looooot ;-)


texts: LineRenderer not working using Vuforia in Unity

texts:
So I'm trying to render a line that shows up when camera sees an image target and moves around with it. Very typical AR application. But my line renderer doesn't seem to show at all.

Here's the code:

using UnityEngine;
using System.Collections;

public class myLine : MonoBehaviour
{
    // Creates a line renderer that follows a Sin() function
    // and animates it.

    public Color c1 = Color.yellow;
    public Color c2 = Color.red;
    public int lengthOfLineRenderer = 20;

    void Start()
    {
        LineRenderer lineRenderer = gameObject.AddComponent<LineRenderer>();
        lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
        lineRenderer.widthMultiplier = 0.2f;
        lineRenderer.positionCount = lengthOfLineRenderer;

        // A simple 2 color gradient with a fixed alpha of 1.0f.
        float alpha = 1.0f;
        Gradient gradient = new Gradient();
        gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
            );
        lineRenderer.colorGradient = gradient;
    }

    void Update()
    {
        LineRenderer lineRenderer = GetComponent<LineRenderer>();
        var t = Time.time;
        for (int i = 0; i < lengthOfLineRenderer; i++)
        {
            lineRenderer.SetPosition(i, new Vector3(i * 0.5f, Mathf.Sin(i + t), 0.0f));
        }
    }
}

and here's my set up:

I also tried attaching the script directly to the ImageTarget and nothing happened.


texts: Race condition implementing World Boss System in Web Browser MMO using PHP

texts:
I am trying to create a world boss system using PHP. But I am having a problem with how to account for all the damage while updating the health of the boss in real-time.

The current damage process is as follows:

Get boss' current HP from database.
Reduce the HP based on the calculated damage.
Update the boss' HP to database.

Example:

Player 1 (P1) attacks the boss. Calculated damage is 10.
The boss' current HP is saved to variable $boss_hp which is 100.
It will now be $boss_hp -= 10. Which is 90.
The boss' HP in database is then updated.

Now, imagine two player attack the boss simultaneously...

P1 attacks the boss. Calculated damage is 10.
The boss' current HP is saved to variable $boss_hp which is 100.
It will now be $boss_hp -= 10. Which is 90.
Before P1 updates the boss_hp in database, P2 also damages the boss.
P2 saved the boss' current HP to his/her own $boss_hp variable which is 100 at the moment.
P2 also performs step 2. $boss_hp -= 10. Which is also 90.
P1 now updates the boss_hp in database (=90).
P2 also updates the boss_hp in database (=90).

The boss_hp should be 80 but the damage of P1 has been neglected since P2 updates the boss_hp last.

How to avoid this problem?


texts: How can I reference for a two cameras on prefab through script?

texts:
I have this script for controlling the cameras :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamerasViewSwitch : MonoBehaviour
{
    public List<Camera> cameras = new List<Camera>();
    public string currentViewMode;

    // Start is called before the first frame update
    void Start()
    {
        if (cameras[0].enabled)
        {
            currentViewMode = "Third Person";
        }
        else
        {
            currentViewMode = "First View";
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            cameras[0].enabled = !cameras[0].enabled;
            cameras[1].enabled = !cameras[1].enabled;

            if (cameras[0].enabled)
            {
                currentViewMode = "Third Person";
            }
            else
            {
                currentViewMode = "First View";
            }
        }
    }
}

In the Assets, I have a prefab with two children's cameras that I want to use in this script.
In this screenshot to show what I mean, I dragged the prefab name Platform to the hierarchy to show where the cameras are. The script is on the object name Cameras Switch.
How do I get these two cameras from the prefab and using them in the script?

I'm using the Platform prefab with this script but the problem is when I'm starting the game the CamerasViewSwitch script is missing the two cameras I'm not to get/find them.


texts:
I am developing a physics based game with spaceships.

A spaceship is constructed from circles connected by joints. Some of the circles have engines attached.

Engines can rotate around the center of circle and create thrust.
I want to be able to move the ship in a direction or rotate around a point by setting the rotation and thrust for each of the ship's engines.

How can I find the rotation and thrust needed for each engine to achieve this?


texts:
I am trying to draw a 3D cube on the screen, using MonoGame.  The cube was created in Blender and exported as an fbx file.  The following is what the cube looks like in VS when opened in the editor:

And this is what it looks like when displayed on screen:

From the research that I've done so far, I believe that I need to apply a texture.  I couldn't see any way to do this in Blender, or in the Content Pipeline Tool, and so I tried the following when drawing the effect:

effect.Texture = _texture;
effect.TextureEnabled = true;

When I run this, I get a runtime error:

  An error occurred while preparing to draw. This is probably because
  the current vertex declaration does not include all the elements
  required by the current vertex shader. The current vertex declaration
  includes these elements: SV_Position0, NORMAL0, COLOR0.

Clearly I'm missing a key part of this puzzle; please can somebody point me in the right direction.


texts: Is Windows window creation faster / more efficient than GLFW window creation?

texts:
Are there any benefits to using Windows window for OpenGL or Vulkan rendering, rather than using GLFW window?

Is there any performance hits when using C++ Window creation over GLFW since it provides OpenGL and Vulkan interface?


texts: Most efficient way to mass render tiles in java slick2D

texts:
So I am trying to make a tile based game, it is rendering about 40 tiles on the screen at once. I get about 40 FPS on an okay computer. When I tell it to not render the FPS jumps to around 400 so I know its something with the rendering. I was wondering if there is a more efficient way to render a lot of tiles. Here is the code for my Tile class :

public class Tile {
    public static Tile empty;
    public static Tile rock;
    public static Tile flower;
    public static Tile grass;

public static Tile[] tiles;

protected boolean solid,breakable;

public static final int TILE_SIZE = 32;

public static final int VOID_TILE = 0, ROCK_TILE = 1,GRASS_TILE = 2,FLOWER_TILE = 3;

private int width = 16,height = 16;

private SpriteSheet image;
private int xCrop,yCrop;
private String path;
private boolean toRender = true;
private int ID;

public Tile(int ID) {
    this.ID = ID;
    path = ("res/spritesheet.png");
    if(ID == VOID_TILE) {
        solid = true;
        toRender = false;
        width = height = 16;
    }

    if(ID == ROCK_TILE) {
        solid = true;
        breakable = true;

        xCrop = yCrop = 1;
        width = height = 16;

        path = ("res/spritesheet.png");
    }

    if(ID == GRASS_TILE) {
        xCrop = yCrop = 0;
        width = height = 16;

        path = ("res/spritesheet.png");
    }

    if(ID == FLOWER_TILE) {
        xCrop = 1;
        yCrop = 0;
        width = height = 16;

        path = ("res/spritesheet.png");
    }
    if(toRender) {
        try {
            image = new SpriteSheet(path,width,height);
        } catch (SlickException e) {
            System.out.println("Error Loading File : " + path);
            e.printStackTrace();
        }
    }

}

public static void initTiles() {
    empty = new Tile(VOID_TILE);
    rock = new Tile(ROCK_TILE);
    grass = new Tile(GRASS_TILE);
    flower = new Tile(FLOWER_TILE);

    tiles = new Tile[] {empty,rock,grass,flower};
}

public void render(int x,int y) {
    if(image!=null)image.getSubImage(xCrop, yCrop).draw(x,y,TILE_SIZE,TILE_SIZE);
}

public void update() {

}

public int getID() {
    return ID;
}

public void setID(int iD) {
    ID = iD;
}

}


texts:
I'm wondering what would be a clever way of making a layered menu system, in terms of what data structures to use.

An example of what I mean: A unit has the ability to construct buildings, and to cast some spells. The selection of buildings and spells are accessed either through pressing a hotkey or clicking an icon in the user interface. What is the best way to achieve this in the code?

I'm thinking something like:

Menu base state: options are A and B. If the players clicks A: change state and display the suboptions of A, and so on. But how is this achieved in the actual code? Perhaps a dict() containing functions:

options = {
           'A' : self.change_state ('a', self.current_state),
           'B' : self.change_state ('b', self.current_state)
          }

def on_key_event(self, key):
     options[key]

def change_state(self, key, state):
     if state == state_1:
          if key == 'a':
              ...

And so on, this seems really tedious and if possible I want to avoid if / else loops and just define everything in the simplest, and shortest manner.

I'm interested in how you would do this, or if you've already made a similar system, how you solved it in your own code.


texts:
I'm trying to mix 2D and 3D using LWJGL.

I have wrote 2D little method that allow me to easily switch between 2D and 3D.

protected static void make2D() {
    glEnable(GL_BLEND);
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    glOrtho(0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 0.0f, 1.0f);

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glLoadIdentity();
}

protected static void make3D() {
    glDisable(GL_BLEND);
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity(); // Reset The Projection Matrix
    GLU.gluPerspective(45.0f, ((float) SCREEN_WIDTH / (float) SCREEN_HEIGHT), 0.1f, 100.0f); // Calculate The Aspect Ratio Of The Window

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    glLoadIdentity();
}

The in my rendering code i would do something like:

make2D();
//draw 2D stuffs here

make3D();
//draw 3D stuffs here

What i'm trying to do is to draw a 3D shape (in my case a quad) and i 2D image. I found this example and i took the code from TextureLoader, Texture and Sprite to load and render a 2D image.

Here is how i load the image.

TextureLoader loader = new TextureLoader();
Sprite s = new Sprite(loader, "player.png")

And how i render it:

make2D();
s.draw(0, 0);

It works great.

Here is how i render my quad:

glTranslatef(0.0f, 0.0f, 30.0f);
glScalef(12.0f, 9.0f, 1.0f);
DrawUtils.drawQuad();

Once again, no problem, the quad is properly rendered.

DrawUtils is a simple class i wrote containing utility method to draw primitives shapes.

Now my problem is when i want to mix both of the above, loading/rendering the 2D image, rendering the quad. When i try to load my 2D image with the following:

s = new Sprite(loader, "player.png);

My quad is not rendered anymore (i'm not even trying to render the 2D image at this point). Only the fact of creating the texture create the issue. After looking a bit at the code of Sprite and TextureLoader i found that the problem appears after the call of the glTexImage2d. In the TextureLoader class:

glTexImage2D(target,
        0,
        dstPixelFormat,
        get2Fold(bufferedImage.getWidth()),
        get2Fold(bufferedImage.getHeight()),
        0,
        srcPixelFormat,
        GL_UNSIGNED_BYTE,
        textureBuffer);

Commenting this like make the problem disappear. My question is then why? Is there anything special to do after calling this function to do 3D? Does this function alter the render part, the projection matrix?


texts: How can I implement smooth tile-based lighting?

texts:
I have been working on a 2D tile game and I have implemented hard-edged lighting:

I want it to be smoothed out a bit. I don't need shadows or anything, just simple lighting. I'd like it to look more like this:

My current system uses light levels for each tile in the world and they are recalculated, when a tile is placed or removed. I'm using batch.setColor(...) to shade the tiles. What is a good way to achieve this smooth lighting?

I don't want to use the light map overlay method, I tried that already and I was not happy with the result. I want to be able to set how much light is able to pass through a block. For examble a dirt block should absorb some of the light, but a glass block should not block any light. This was not really possible with the light map overlay method. UPDATE: I missunderstood what this method actually is. I understand now. I was thinking the wrong way. Sorry!


texts: How to make Unity game moddable with scripting in a friendly way?

texts:
I am building a game in Unity using C# and visual studio. I want to make it possible for users to write code in some scripting (for modding purposes) without necessarily opening the source. What are my best options?

I'd prefer well-supported and battle-tested options that integrate well with Unity and visual studio, but I am willing to do a fair amount of work myself as long as it makes scripting as seamless as possible for future modders.


texts: How can I update a Stage-based HUD from another Stage's Actor in libGDX?

texts:
I feel like this is a simple problem, but I'm having issues finding the correct search terms.

I have a Screen that includes two Stages.

The first, stage, contains a number of objects deriving from Actor and added via the standard stage.addActor(Actor). This is for the actual game objects.
The second, hudStage, consists of a single Table actor. This table includes a button as well as two Labels. This is for the static user interface/HUD.

I'm handling touch events on my custom actors in the game stage like the following:

public class GameObject extends Actor {
    private final static String TAG = GameObject.class.getName();
    // ...

    public GameObject() {
        // ...

        addListener(new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log(TAG, "touchDown on GameObject actor: <" + x + "," + y + ">");
                return super.touchDown(event, x, y, pointer, button);
            }
        });
    }

This works perfectly and logs what I need. However, I would now like to update the HUD with information about the object the user touched.

My screen has defined the Label I want to update (added via hudStage), but I'm not sure how to go from an actor in stage to the screen, or to the hudStage label.

public class GameScreen implements Screen {
    Stage stage;
    Stage hudStage;
    // This is the label I want to update.
    Label infoLabel;
    // ...
}

I know I can call setText(String) on the label, but I'm not sure the best way to bubble the click up. Plenty of examples have simplified versions where objects are defined in the main class (in my case, GameScreen) and are able to refer to them that way, but I've already broken these apart.

I started to look at creating a custom event that my actor could trigger, and that the stage would handle, but documentation is sparse and I'm not sure this is required.

I've also thought about scrapping the idea of having a label in the hudStage and instead having my actor draw text where the HUD would have. However, from what I continue to see, I think Scene2D is the right direction to go for the UI.

Thanks!

EDIT: What I'm looking for:

An actor in GameScreen.stage is target of a touchDown event.
Logic in actor fires and updates object.
touchDown event in actor finishes by updating infoLabel in GameScreen.hudStage or updates String value in GameScreen (if easier, I'll go this route).


texts:
I want make 2d open box animation. Like cs-go open keys or other random box.
I need the basics of implementation it and i want get more information about it. Thanks.

Upd:
Steps.
I have array of elements.

I press to button and shuffle array.

I get random element from array by weight.

All elements in array have images.

So , after i press button all images start move with some accelerate to left or right. 6 images move to left. And what is next ? I need get random items images while acceleration is not end ? Or what ? I need logic example.

My example realization(I don't know working it or not): I need add to array new items while acceleration is enable or what ?
Or after i get random item by weight, i need sort array and past it item to last position and add other random items to this array. And after all i need loop to this array to last item. And when loop in last position i show it item in screen ?

I really don't understand how it working.. D:


texts: Problem with collisions detection on canvas platformer

texts:
Having a lot of trouble with my collision detection in my platformer. If you go straight to the right the block will float.  Also the corners let the block sink right through and the walls are sticky. It's a bit of a mess. I know for the floating my gravity is a big issue. If anyone could help me out i'd be so so happy.

Heres the collision code:

  const calculatedTileSize = 1.0 / mapTileSize;
  const nextX = guy.x + guy.velX;
  const nextY = guy.y + guy.velY;

  const currentMinX = (guy.x * calculatedTileSize) | 0;
  const currentMaxX = ((guy.x + guy.width) * calculatedTileSize) | 0;
  const currentMinY = (guy.y * calculatedTileSize) | 0;
  const currentMaxY = ((guy.y + guy.height) * calculatedTileSize) | 0;

  const nextMinX = (nextX * calculatedTileSize) | 0;
  const nextMaxX = ((nextX + guy.width) * calculatedTileSize) | 0;
  const nextMinY = (nextY * calculatedTileSize) | 0;
  const nextMaxY = ((nextY + guy.height) * calculatedTileSize) | 0;

  // X axis collision
  if (guy.velX !== 0.0) {
    for (let i = nextMinX; i <= nextMaxX; i++) {
      for (let j = currentMinY; j <= currentMaxY; j++) {
        if (map[j][i]) {
          guy.velX = 0.0;
          break;
        }
      }
    }
  }

  // Y axis collision
  if (guy.velY !== 0.0) {
    for (let j = nextMinY; j <= nextMaxY; j++) {
      for (let i = currentMinX; i <= currentMaxX; i++) {
        if (map[j][i]) {
          guy.velY = 0.0;
          physics.gravity = 0;
        } else {
          physics.gravity = 0.4;
        }
      }
    }
  }

The full game is in this codepen:

https://codepen.io/charlie1172/pen/OeGdvJ


texts: Entity-Component-System data storage design

texts:
I'm working on an ECS and I've already read a lot of articles about it. Most of these articles are talking about a simple case (store data contiguously, read it in a single for loop). However the real world is more complex: one system reads multiple components and those have to be read fast.

So I'm thinking on a new data storage model but before I start to implement it, I'd like to know what do you think: I'm not sure if this design would solve any (future) performance problem (I'm thinking about cache coherency, prefetching, etc. optimization).

So the basics are the same:

Each Entity is a handle (id + version number together).
Each Component is a(n ideally small) POD.
Each System is responsible for the processing of a set of components.

The first idea in every article is to store the component data in an array (of each type) and use a fast-lookup map (eg. hash_map) for the entity_id->component_id relation.

Eg. the Position component pack looks like this:

component data:
[pos_0][pos_1]...[pos_n]

entity->component map:
[entity_0 -> 1][entity_2 -> 0]...[entity_m -> n]

This works well if the systems are reading a single type of component linearly. If a system wants to read another component as well, it will generate at least two additional cache misses:

one for the entity_id->component_id lookup (to find the other component from the entity)
and one for the actual component data

So my idea is that instead of separating the components I could create groups. Each group has the same behaviour like before (the data laid out contiguously and an entity_id->component_id map is stored for fast component lookup) but the data stores multiple component data.

The point is that the component data is stored in the same order as the other components so if a system wants to read eg. the Position + Velocity component set it can iterate linearly on the array. Each component type has an offset to indicate where it starts on the big array.

So the Position+Velocity group looks like this:

component data:
[pos_0][pos_1]...[pos_n][... some space ...][vel_0][vel_1]...[vel_n]... and so on

entity->component map:
[entity_0 -> 1][entity_2 -> 0]...[entity_m -> n]

And if I'm interested in a component set of a single entity, I can use the map to find the component id then read the components using this id:

component_id = find(entity_id);
comp_0 = data[offset_of(comp_0_type) + component_id]
comp_1 = data[offset_of(comp_1_type) + component_id]

The biggest drawback is the larger array: when the array has to grow it has to allocate and copy more data at once. But IMHO the whole idea could work because most of the time (in my experience at least) an entity's components are not changing at run-time.

Note:
I tagged c++ as well, because I'm using c++.

Edit

Actually I've found a problem with this approach. This way the components cannot refer to each other. Eg a Transform component is responsible for structuring the "objects" in a tree, so each Transform component has a parent and a children property. However with this design I don't know how I could refer to the other Transform component since it can be in any group's array.

Edit 2

For the first iteration I'm going to implement a simple design, similar to the "Packed Array" described here.


texts: Are there any hex tile sizes where both width and height are integers?

texts:
I'm trying to figure out the optimal width and height (in pixels) to start building hex tiles for game development. My preference is for "flat topped" hex grids, but the math is similar for both.

I am looking for an "optimal" tile size that allows both the width and the height of the tile to be a rounded pixel number, based on the fact that height = sqrt(3)/2 * width.

My math skills being virtually nonexistent, I just ran a brute force script that ran through widths from 1 to 1024 and did not come up with a single value for w where h was an integer. Is this really the case? How does anyone create pixel-perfect hex tiles if there's no even width & height size that can accommodate a perfect hex aspect ratio?


texts: A class for all levels or for each level an own class?

texts:
My Game become more complex with each new Level or Map that I design.
The game is an basic rpg game like Pokemon.

For now I have one class that organize all Maps but different maps have special features and different Monsters.

Better use for each Map an own Class and have duplicated code
or is there a specific pattern for this?

Edit:
My Problem: I can load the new map and play but all maps have different monsters and different events. I can't put all of them in the Game class and check all the time everything.

my class diagram in simple:


texts: Trying to find a function to calculate attribute changes in a game

texts:
I'm coding a game where after every year depending on results the attributes of characters change. The game is a movie business simulator and here is a example of the ugly code I have in place now:

        if (movie.Reviews.Avg > 8.5f)
        {
            movie.Producer.Reputation += 6f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 7.5f)
        {
            movie.Producer.Reputation += 5f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 6.5f)
        {
            movie.Producer.Reputation += 4f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 5)
        {
            movie.Producer.Reputation += 1f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 4.5)
        {
            return;
        }
        else if (movie.Reviews.Avg > 4)
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 6f;
            return;
        }
        else if (movie.Reviews.Avg > 3)
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 5f;
            return;
        }
        else if (movie.Reviews.Avg > 2)
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 4f;
            return;
        }
        else
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 3f;
            return;
        }

Few problems I have with this code:
1. Reputations balloon. Good AI producers make good choices so their movies get good reviews and their reputation goes even higher.
2. Because reputations keep growing the absolute changes in attributes get smaller and moving up in ranks gets way too slow and hard.

What I am looking from the function:
1. Range is 0-10.
2. At the top of the range growth is slow even with great reviews, but if your movie gets bad reviews the decline is sharp. And the opposite for the bottom of the range.


texts: 2D Scrollable View with Matrix of Numbers on Android

texts: I would like to implement a 2D, scrollable view which can be scrolled horizontally, vertically or even diagonally (similar to a zoomed image which can be scrolled in any direction, but has bounds). In that scroll view, I would like to have matrix of numbers. Which component(s) should I use for this purpose.


texts: How can I make an object change direction?

texts: I have a moving cube that, when it moves over an arrow, should change its direction to the direction of that arrow. What would I need to do in order to accomplish this?


texts: D3D11 Can only Pixel Shader and Compute Shader stages write to buffers?

texts:
I am reading Practical Rendering and Computation with Direct3D 11.
In the book the D3D11 pipeline is often described with this image:

In the Chapter about resources, Paragraph about buffers, I understood that the only stages that can write to buffers are the Pixel Shader and the Compute Shader, using Unordered Access Views.
Is it correct? If so, why? Is it because of the inherent architecture of GPUs?

Then, what would be the typical method to output data from a different stage?
For example, how could one get the result of a computation done in the vertex shader, without needing to pass through the other stages?


texts: Unity 4 - Some Rigidbodies Won't Fall Asleep

texts:
I'm having this problem in the free edition of Unity 4.1 where rigidbodies aren't falling asleep (and yes, I've tried playing with the sleepVelocity and sleepAngularVelocity values!). I've read the docs at http://docs.unity3d.com/Documentation/Components/RigidbodySleeping.html but cannot figure out the problem.
Here is a screenshot demonstrating my problem:
Rigidbody Sleep Diagram http://uberlethal.com/random/rigidbody_sleeping.png
I wrote a script that is attached to the rigidbodies in question, which sets the material color to red if the rigidbody is currently asleep or green if it is awake. The screenshot was taken when all objects were at rest. As you can see, not all of the gameobjects are sleeping. Each piece of debris you see on screen is its own gameobject with a rigidbody and collider.
The Unity docs I linked to above state the following:

Rigidbodies automatically wake up when:

another rigidbody collides with the sleeping rigidbody
when adding forces.

Perhaps some clarification on the above might help solve this issue: If two rigidbodies are touching when they fall to "rest", will they never stay asleep? Put another way, would they just keep interrupting each other's sleep? As for the "adding forces" part, do sleeping rigidbodies awake only when forces are added directly to them, or when any force is added to any object (this is important because I am using a rigidbody character controller which moves via AddForce() calls)
I have tried manually sleeping objects myself with undesired results. What usually happens when I do this is that some objects will remain suspended in the air.
Let me know if you need other details - I have tried a great deal of things.


texts: How do I avoid fetching duplicate tetromino shapes from a Shape array in Unity/C#?

texts:
I'm working in C# in Unity on a tetrominoes game. I have seven basic shapes (I, J, L, O, S, T, Z) but each of the four component squares on each shape is labelled with an identifier unique to the shape set. So the shapes include, e.g., an S-1,2,3,4, S-5,6,7,8, S-9,10,11,12, J-13,14,15,16, J-17,18,19,20, Z-21,22,23,24....

Currently, in my Spawner class, I have the following to fetch a shape randomly from the shape array, m_shapeSet1:

public class Spawner : MonoBehaviour {

public Shape[] m_shapeSet1;

Shape GetRandomShape()
{
    int i = Random.Range(0, m_shapeSet1.Length);
    if(m_shapeSet1[i])
    {
        return m_shapeSet1[i];
    }
    else
    {
        return null;
    }
}

I thought it would be simple to use m_shapeSet1.RemoveAt(i) before the final closing brace after each fetch to avoid fetching, and later spawning (there is another function to spawn shapes), a duplicate shape. BUT, Visual Studio responds with: (1) the RemoveAt request is unreachable and (2) Shape[] has no definition for RemoveAt and no extension for it.

(I'll have to add a Do While or another control to this as I cannot retrieve a shape from the empty array I hope to create once I'm able to get only a unique shape.)

Anyway, how do I get a shape without duplication?


texts: NoSQL (CouchDB) database design for MMORPGs

texts:
Are there any pratical examples of database implementation for an MMORPG in CouchDB? Even a detailed thesis? I've looked but found very little on practical examples and not even find any good UML examples and plus I see a little bit of an issue with the lack of schema and design by UML. Maybe It's more of a paradigm change but I'm ideally looking for something that has things like:

Users
Quests (multipart states)
Characters
NPC states
Items

Just to get started...regards


texts:
XNA 4 includes the Microsoft.Xna.Framework.Audio.Microphone class which can seemingly read the raw sound data off the microphone via its API as documented:

GetData - Gets the latest recorded data from the microphone.
GetSampleDuration - Returns the duration of audio playback based on the size of the buffer.
GetSampleSizeInBytes - Returns the size of the byte array required to hold the specified duration of audio for this microphone object.

Can I read sound data using this class, record it in an array and then play it back? On the Xbox 360?


texts: AI control for a ship with physics model

texts:
I am looking for ideas how to implement following in 2D space. Unfortunately I don't know much about AI/path finding/autonomous control yet.

Let's say this ship can move freely but it has mass and momentum. Also, external forces might affect it (explosions etc). The player can set a target for the ship at any time and it should reach that spot and stop.

Without physics this would be simple, just point to the direction and go. But how to deal with existing momentum and then stopping on the spot? I don't want to modify ship's placement directly.

edit: Just to make clear, the physics related math of the ship itself is not the problem.


texts: How do I make a rainbow hue shift over time on text?

texts:
What I'm trying to do is make a Text object have an animation that allows for the hue of the color to go all the way up and loop back around, so it creates a cool rainbow thing.
I've looked on google for a solution but the solution I found only worked in older versions of Unity, which were used back in 2015.  What I found
Any help would be appreciated!


texts:
I am learning how to code by programming easy, 2D games. Here I want to try to get only a map, like in strategy games (2D isometric) and put new objects (pictures) on it.

In short: I want load a big picture and put little pictures on this big picture.

My thought was:

Find a big map picture. (or make it with Photoshop)
Put a grid-layout over that base (this will not be visible to the player).
Put smaller objects (as pictures) on this map using this grid-layout.

Is it possible to make it like this, or are there better solutions?


texts: What is the status of Monogame now that XNA has been discontinued?

texts: XNA has officially been discontinued, with support no longer being offered by Microsoft. Does this mean that Monogame has died also? I see that the site still says it is based upon XNA 4. What is the official status of Monogame?


texts: Inline If failing to update variable value

texts:
So, I have a toggle button to change a bool value, in this script 't1Bool'. The toggle button is working because when I use a Debug.log I can see the value changing from true o false when I press the button. When using the Debug.log with the variable turbina1 the value is always zero. I already checked the if condition syntax and don't know why this value is not being updated.

using System;
using UnityEngine;
namespace Assets.Code.PowerPlants
{
    public class HydroElectric
    {
        public bool t1Bool;
        public bool t2Bool;
        public bool t3Bool;

        int turbina1;
        int turbina2;
        int turbina3;

        public float prod;

        public HydroElectric ()
        {
         t1Bool = true;
         t2Bool = true;
         t3Bool = false;
         prod = 0f;
        }

        public float HydroControlPanel ()
        {
            turbina1 = t1Bool ? 2 : 0;
            turbina2 = t2Bool ? 3 : 0;
            turbina3 = t3Bool ? 1 : 0;

            prod = turbina1 + turbina2 + turbina3;
            Debug.Log (turbina1);
            return prod;
        }
    }
}

This is the code for the button:

public void ShowIt()
{
            ec.t1Bool = GUI.Toggle (new Rect (25, 55, 100, 50), ec.t1Bool, "Turbina 2 MW");

            ec.t2Bool = GUI.Toggle (new Rect (25, 95, 100, 50), ec.t2Bool, "Turbina 3 MW");

            ec.t3Bool = GUI.Toggle (new Rect (25, 135, 100, 50), ec.t3Bool, "Turbina 1 MW");

            GUI.Box (new Rect (Screen.width - 100, 60, 80, 25), ec.prod.ToString ());      // PRODUCED ENERGY

        }

This is where the object instance is created (it is in the same script as the button):

public class PlayState : IStateBase
    {
        private StateManager manager;
        private HydroElectric ec;
        public PlayState (StateManager managerRef)
        {
            manager = managerRef;
            Debug.Log ("Constructing PlayState");
            ec = new HydroElectric();
        }

Any hint?


texts: How to keep track of camera's rotation while it's being rotated?

texts:
I'm building a 2D game where the sole interaction of the player is rotating what they can see (this is currently the camera, though it could be the world) by plus or minus 60 degrees.

My current approach has their input rotating the camera. The issue I'm having is that I'm finding it impossible to keep track of how many degrees they've rotated it, since the camera is rotating and losing its initial position.

(I'm using libgdx, however, I think this problem is framework independent.)

Edit:

To help with the understanding, let me provide an example. Picture yourself in a school playground. You want to turn 90 degrees. To help you keep track, you mark the ground with the chalk in your hand. Turning 90 degrees is now easy since you have a reference point.

Now imagine you're in space and trying to do the same thing. Instead of chalking the ground, you chalk yourself. It's now nigh impossible to know how much you turn by when you do.


texts: How do I make an actor move to the foreground temporarily in LibGDX scene2d?

texts:
I have an inventory UI which is a table in scene2d. Then the table had a bunch of Containers which are basically inventory slots. They have a transparant grey background color. Then in each container is an ItemStack with a picture of an item and a stacksize. When I pull this ItemStack over a container that was created later, it moves behind the container and the transparant grey background will be in front of the item picture. How do I temporarily (or permanently) move it to the foreground so it doesn't matter in front of which container I drag the item?

Example of what happens:
https://i.imgur.com/yq4njex.gifv

This is how I create the containers:

// Create inventory slots
table.row();
inventorySlots.clear();
for (int i = 0; i < inventory.getInventorySize(); i++) {
    if (i % SLOTS_PER_ROW == 0) table.row();

    Container cont = new Container();
    cont.fill();
    cont.background(Utils.createDrawable(1, 1, new Color(0, 0, 0, 0.4f)));

    inventorySlots.add(cont);
    table.add(cont).prefHeight(50).prefWidth(50).pad(5);
}

After that I add each ItemStack to the list of containers/inventoryslots like this:

// Add ItemStacks from Items to their respective slot
ArrayList<Item> items = inventory.getItems();
for(Container slot : inventorySlots) {
    Item item = items.get(inventorySlots.indexOf(slot));

    if(item != null) {
        ItemStack itemStack = new ItemStack(item);
        addInventoryEvent(itemStack, items);
        slot.pad(5);
        slot.setActor(itemStack);
    }
}


texts: What to do with d3dx9math.h when converting to DirectX11?

texts:
I'm converting an old game from DirectX9 to DirectX11 and I have a question: What I should use instead of d3dx9math.h?
Do I have to convert everything for DirectXMath.h(XNAMath), or I can continue with my old d3dx9math.h or even d3dx10math.h?


texts: Both Trigger and Collision BoxCollider2D

texts:
My Player sprite needs to collide with some objects and be unable to pass through them and in other cases detect when it passes through some object (e.g. some non-fatal enemies and some one-way barriers).

How do I test what an object is and make enforce one collision type or the other?


texts: Drawing a textured 3D object breaks SFML text render

texts:
I writing a OpenGL game using SFML.

I'm using the push/pop function to combine OpenGL with SFML like the tutorial SFML+OpenGL but, when I added textures to my model, the SFML text rendering appears broken and wrong rendered.

The simplified loop I used is:

while( true ){
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glUseProgram( programID );

    // Draw the 3d textured object
    glActiveTexture( GL_TEXTURE0 );
    glBindTexture( GL_TEXTURE_2D, tex_2d0 );

    object.draw();

    window->pushGLStates();

    window->setView( view );
    window->draw( text );
    window->setView( window->getDefaultView() );

    window->popGLStates();

    window->display();
}

My 3d model is draw right but something in the glActiveTexture/glBindTexture mess up the text in the SFML part.

If I add:

glActiveTexture( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );

And the end of my OpenGL rendering code, nothing is fixed anyway.


texts: Do I need to "use" the shader program when buffering and defining VBO data?

texts:
I'm trying to wrap my head around the relation between a GL "program", and the VAOs, buffers, textures, etc. I don't quite understand when I need to "use" my shader program, and when (if ever) I need to "un-use" it?

So when do I need to use the shader program (i.e. invoke glUseProgram), exactly? Does my shader program need to be in "use" when:

Creating and binding VAOs?
Creating and binding VBOs?
Buffering data to VBOs?
Defining vertex attributes (i.e. invoking glVertexAttribPointer)?


texts: Unity - Missing Render Setting from Edit menu

texts:
Where I can select Render Setting from Edit menu from Unity5? It looks missing.

It suppose to be like this one.

Please advice. Thank you.


texts: How can I avoid sending the full game state so often?

texts:
I'm making a real-time 2D MMORPG in Java. Currently data all surrounding NPCs' and players' data is sent so frequently that the client crashes—it can't handle the data quickly enough. I'm sending data so frequently to make sure the game state stays up to date.

Is there an alternative? Should I make it send information only when needed, like when health is lost or something moves, instead of updating the whole object every time? How do I do this?


texts: Does SFML render it's graphics using OpenGL internally?

texts:
By that, I mean that SFML has an abstraction for OpenGL? Sort of like SDL's blit functions, but using OpenGL internally?

"Yes SFML uses OpenGL for all the graphical stuff. "

Received this comment in an earlier question, which sort of baffled me since I find nothing about it.


texts: Showing a mesh on a Screen Space Overlay

texts:
I have created a Screen Space Overlay.
This Screen Space Overlay panel hosts 3 Texts. This works fine.

Then I tried to show a mesh on this Screen Space Overlay.

First, I simply added it as a child of the panel.
Since this didn't show it, I added a Canvas Renderer to the mesh.
This also didn't help.

What might be the culprit here?

Thank you!

ps: What I'm trying to achieve is a mesh rotating in front of the user's eyes like this:

This a sequence of what happens in the original scene that I try to rebuild:

One can see that as soon as the item is being inspected, a (very likely a screen space) overlay is shown, and the original scene gets dark.
Also the selected item is shown and is rotated continously.

I imagined that it is a screen-filling screen space overlay which has an image. The upper menu of the image is filled with a color with 50% alpha in order to blend the background out.

I imagined that the weapon was then rendered in front of the screen space overlay image. If it was behind the the screen space overlay, it would be dim / greyed out like the rest of the scene.

That's how I came to think that the weapon was part of the Screen Space Overlay.

I know now that this isn't so because a Mesh Renderer can't be rendered in the UI "pass", but I would anyway like to know how this could be done.

Edit:
Here is a screenshot of an HDRP camera:


texts: How do I find a point given an angle and distance to it?

texts:
I'm working on a school project creating a tank team in the programming game Robocode. (It's a tank battle game with self-programmed bots, in Java).

I'm programming a scout bot that scans, finds enemies and reports them to the commander bot. I only have the distance and angle to the scanned enemy bot. How can I find its X,Y-position using only these known variables?

Here's a diagram:


texts:
Now it will move all the objects of allLines and instancesToMove at the same time.
But I want to take each time one object from the allLines and one from the instancestoMove and move this two together then the next two objects and so on.

if (animateLines)
        {
            counter++;
            for (int i = 0; i < allLines.Count; i++)
            {

                endPos = allLines[i].GetComponent<EndHolder>().EndVector;
                Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
                Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

                allLines[i].GetComponent<LineRenderer>().SetPosition(1, tempPos);

                instancesToMove[i].transform.position =
                    Vector3.MoveTowards(startPos, endPos, counter / 25f * speed);

                if (Vector3.Distance(instancesToMove[i].transform.position, endPos) < 0.1f)
                {
                    DestroyImmediate(instancesToMove[i]);
                    instancesToMove.RemoveAt(i);
                    DestroyImmediate(allLines[i]);
                    allLines.RemoveAt(i);
                }
            }
        }

Both allLines and instancesToMove are List


texts: Using a permutation table for simplex noise without storing it

texts:
Generating Simplex noise requires a permutation table for randomisation (e.g. see this question or this example).

In some applications, we need to persist the state of the permutation table. This can be done by creating the table, e.g. using

def permutation_table(seed):
    table_size = 2**10  # arbitrary for this question
    l = range(1, table_size + 1)

    random.seed(seed) # ensures the same shuffle for a given seed
    random.shuffle(l)
    return l + l  # see shared link why l + l; is a detail

and storing it.

Can we avoid storing the full table by generating the required elements every time they are required?

Specifically, currently I store the table and call it using table[i] (table is a list). Can I avoid storing it by having a function that computes the element i, e.g. get_table_element(seed, i).

I'm aware that cryptography already solved this problem using block cyphers, however, I found it too complex to go deep and implement a block cypher.

Does anyone knows a simple implementation of a block cypher to this problem?


texts: How to make randomly placed objects not on top of each other?

texts:
I randomly instantiate game objects, to create a dynamic "sky map". But some planets appear on top of another ones. I'm trying to solve this problem with Collision detection and Colliders, but it doesn't seem to work. How to solve this problem? Maybe there is a better and easier way to do this?

Here is the code I use:

Instantiating:

for (int i = 0; i<planet_one_count; i++) {
            var planets = Instantiate (planet, new Vector3 (Random.Range (-9.0F, 9.0F)+(Random.value), Random.Range (-4.0F, 3.0F)+(i*Random.value), 0), new Quaternion (0, 0, 0, 0)) as GameObject;
            planets.transform.localScale = planets.transform.localScale*Random.Range(0.75f,1);
                }
        for (int i = 0; i<cometcount; i++) {
            var comets = Instantiate (comet, new Vector3 (Random.Range (-9.0F, 9.0F)+(Random.value), Random.Range (-4.0F, 3.0F)+(i*Random.value), 0),Quaternion.Euler(0,0,Random.Range(-34,-24))) as GameObject;
            comets.transform.localScale = comets.transform.localScale*Random.Range(0.75f,1);
        }
        for (int i = 0; i<planet_two_count; i++) {
            var planets_two = Instantiate (planet_two, new Vector3 (Random.Range (-9.0F, 9.0F)+(Random.value), Random.Range (-4.0F, 3.0F)+(i*Random.value), 0), new Quaternion (0, 0, 0, 0)) as GameObject;
            planets_two.transform.localScale = planets_two.transform.localScale*Random.Range(0.75f,1);
        }

Collision:

void OnCollisionStay2D(Collision2D coll){
    coll.gameObject.transform.position = new Vector3(coll.gameObject.transform.position.x+0.1f,coll.transform.position.y+0.1f,0);
}


texts: I'm thinking of going back to xna and c# because I have used java 2d, slick 2d and some other libraries. I started off with xna and c# but ignored it for java. I'm thinking of going back, but I see xna isn't being developed anymore. I read there is away to convert it to monogame but seems very complicated. XNA look fairly easy, yet I havn't toyed with monogame yet. So what I want to know , is monogame related to xna or close in coding? Would it be easy to understand if you're good with xna?


texts:
I'm currently attempting to create a cartoon-ish water shader with a shoreline. After looking around trying to find out how other games do it i figured out it has something to do with getting the distance from the depth map (which doesn't include the water when it's render queue is set to transparent) and the and the world position of the current pixel.

From certain angles i'm actually getting very close to the desired result as show here:

The topmost island almost has the desired result, but as you can tell, the closer it gets to the camera, the more out of place the effect becomes.

here's a zoomed out top down view illustrating the problem

as per request, here's what the terrain looks like beneath the water surface (animated gif)

and of course, here is my shader code:

Shader "Custom/CartoonWater" {
 Properties {
     _Color ("Color", Color) = (1,1,1,1)
     _Glossiness("Smoothness", Range(0,1)) = 0.5
     _ShoreFade("Shoreline Distance", Float) = 1
 }
 SubShader {
         Tags{ "Queue" = "Transparent" "RenderType" = "Transparent" }
     LOD 200

     CGPROGRAM
     // Physically based Standard lighting model, and enable shadows on all light types
     #pragma surface surf StandardSpecular

     // Use shader model 3.0 target, to get nicer looking lighting
     #pragma target 3.0

     sampler2D _CameraDepthTexture;

     struct Input {
         float3 worldPos;
         float4 screenPos;
     };

     half _Glossiness;
     fixed4 _Color;
     float _ShoreFade;

     void surf (Input IN, inout SurfaceOutputStandardSpecular o) {

         o.Albedo = _Color.rgb;
         o.Smoothness = _Glossiness;

         fixed4 depth = tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(IN.screenPos));

         o.Albedo = _Color;
         if (distance(LinearEyeDepth(depth), distance(_WorldSpaceCameraPos, IN.worldPos)) < _ShoreFade) {
             o.Albedo = fixed4(1, 1, 1, 1);
         }

     }
     ENDCG
 }
 FallBack "Diffuse"
 }

any help is greatly appreciated :) thanks in advance.


texts:
I am designing a trading card game for mobiles, with the possibility to add cards to your collection using Gems, aquired through victories and inapp purchases.

I am thinking to increase the spread of the game with a tracking system on game invites, enabling the user to invite a friend to play the game. If the friend doesn't own the game client (which is free) he will be offered to download it. If he joins the game, the original player earns X amount of gems as an reward.

There can only be one player per mobile device, which should rule out some harvesting.

My question is, how do you think the structure of this would be recieved ? All invites are mail based, unless the player already exists in the game world (then he gets a ingame invitation.)

I have set a flood filter, so a player can only invite a friend (without the client installed) once a month.


texts: Perform intersection (horizontal and vertical) checking in raycasting

texts:
I want to check the horizontal and vertical intersections on my raycasting view, and I can't exactly understand what is ALPHA using this drawing

source : https://www.permadi.com/tutorial/raycast/rayc7.html

I wrote something that makes the walls straights and with less stairs on top and bottom, but i have some columns which go out of the view row, i can't figure out where i failed my operations (rounds)

this is the code of the vertical and the horizontal intersections :

static inline void      inter_hor(t_wolf3d *w, int i, double angle){
t_vec2f a; // first intersection point
t_vec2f o; // offset
double  tangent;

tangent = ttan(angle) + 0.001;
a.y = (angle <= 180) ? floor(w->cam->position.y / 32) *
32 - 1 : ceil(w->cam->position.y / 32) * 32 + 32;
o.y = (angle < 180) ? -32 : 32;
o.x = (angle < 90 || angle > 270) ? 32 / tangent : -32 / tangent;
a.x = (angle != 180.0 && angle < 359.97) ? w->cam->position.x + (w->cam->position.y - a.y) / tangent :
w->cam->position.x + (w->cam->position.y - a.y) / -tangent; //w->mini_h is the w->map->h  * 32 and so on for w->mini_w
a.x = (angle >= 179.97 && angle <= 180) ? w->cam->position.x + (w->cam->position.y - a.y) / -tangent : a.x;
if (ceil(a.x / 32) < 0 || ceil(a.x / 32) >= w->map->w)
    a.x = (ceil(a.x / 32) < 0) ? 0 : w->mini_w - 1;
while (w->map->board[(int)a.y / 32][(int)a.x / 32] == 0)
{
    a.x += ((angle >= 90 && angle < 180) || angle >= 270) ? -o.x : o.x;
    a.y += o.y;
if (ceil(a.x / 32) < 0 || ceil(a.x / 32) >= w->map->w)
    a.x = (ceil(a.x / 32) < 0) ? 0 : w->mini_w - 1;
    if (a.y < 0 || a.y > w->mini_h - 1)
        break;
}
w->cam->interh[i].x = a.x;
w->cam->interh[i].y = a.y;}
static inline void      inter_ver(t_wolf3d *w, int i, double angle){
t_vec2f a; // intersection point
t_vec2f o; // offset
double  tangent;

tangent = ttan(angle) + 0.001;
a.x = (angle >= 90 && angle < 270) ? ceil(w->cam->position.x / 32) *
32 - 1 : floor(w->cam->position.x / 32) * 32 + 32;
o.x = (angle > 90 && angle < 270) ? -32 : 32;
o.y = (angle > 0 &&  angle < 180) ? -32 * tangent : 32 * tangent;
a.y = (angle != 270 && angle != 90) ? w->cam->position.y + (w->cam->position.x - a.x) * tangent :
w->cam->position.y + (w->cam->position.x - a.x) * -tangent;
if (ceil(a.y / 32) < 0 || ceil(a.y / 32) >= w->map->h)
    a.y = (ceil(a.y / 32) < 0) ? 0 : w->mini_h - 1;
while (w->map->board[(int)ceil(a.y / 32)][(int)a.x / 32] == 0)
{
    a.y += ((angle > 90 && angle < 180) || angle > 270) ? -o.y : o.y;
    a.x += o.x;
    if (ceil(a.y / 32) < 0 || ceil(a.y / 32) >=  w->map->h)
        a.y = (ceil(a.y / 32) < 0) ? 0 : w->mini_h - 1;
    if (a.x < 0 || a.x > w->mini_w - 1)
        break;
}
w->cam->interv[i].x = a.x;
w->cam->interv[i].y = a.y;}

I could use the dir.y / dir.x computed before for my tangent, but i didn't cause i had some divisions by zero when my rays was facing at 180, 360, 0 degrees, angles are complexes and i dont understand completely the vectors method to do that way; these are some screeshots :


texts:
For training a machine learning algorithm, we need to render some geometry in OpenGL without any hardware rendering support (no graphics card).
So we were thinking of rendering in pure software, and we have looked at Mesa already.
It seems like it is capable of rendering in pure software, but so far, we only get OpenGL 2.x, whereas we need OpenGL 3.3 .

Does anyone know if that is possible? and if so, how?
We seem to run into stumbling blocks all the time.

(Background, why we want to do that: for training the learning algorithm, we need to perform a lot of runs of our software on a PC cluster, which do not allow rendering in hardware.)

Any hints, ideas, and pointer will be appreciated.


texts:
I'm a programming newbie.

I have a Quadtree. I created a TreeNode class that the Quadtree will use as nodes. I have spriteNode that inherits from TreeNode.

However, I also have several sprite types inheriting from a Sprite class that I use to instantiate specific sprites.

When I am creating spriteNodes for example I have to cast each specific sprite type to it's parent Sprite class. When I put spriteNode into the quadtree I have to cast the spriteNode to be of type TreeNode so I can generalize the quadtree as much as possible to take different types of data.

I'm not sure if this is a great way of storing all your sprite / map data inside a quadtree, because setting it up requires a lot of explicit casts (even though cast up a level are safe).

Is my OO design approach to storing sprite / map data inside the quadtree the correct way to handle a large quadtree of data? Or is there a better, more standard way of doing things?


texts:
I'm having a problem with filters/masks when raycasting.

I've created a LayerMask and then in the inspector selected the layer I want to ignore when Raycasting. however then I print out the name of the object hit by the raycast I am still getting hits on objects on the layer masked out, as well as on other layers.

public LayerMask rayMask;

RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit,rayMask)){
    Debug.Log (hit.collider.name);
}

I have paused the Game and checked that the object I'm getting a hit on is indeed on the layer in the mask.


texts: Unity: Water shader vertex offset - how to add mesh collider which updates with vertex offset?

texts:
I have written a shader (in the new LWRP shader graph) which simulates an ocean with vertices which offset to create a moving "waves" effect.

I believe that in order to have objects "float" on my moving waves, I shall need to create a mesh collider which is a trigger (please correct me if I'm wrong) which updates with the moving vertices of the mesh as per direction from the shader.

How is such an effect possible? Am I taking the correct approach here? Please advise :)

Many thanks in advance!!

(the original model for the water is a plane which has been subdivided multiple times to provide suitable resolution for the vertices to be offset)


texts: Unity 5.x - Editor only constructor/initilization event

texts:
I have three scripts:

Level - Represents a Tile Based level.

LevelEditor - Custom Editor for Level.

Tile - A non monobehaviour class for storing tile information.

Level contains an array of Tiles to be allocated with 'new'. To avoid putting 'If array != null' everywhere in the code, I want to initialize the array simply to a size of 0 before anything else is ran.

However, I do not want this initialization to happen at run time, just only for editing purposes.

Is there some event I can use that will run before Level.OnDrawGizmos(), and also not be part of runtime code? Or is LevelEditor.OnEnable() the best I can do, with some checks in Level.OnDrawGizmos()?


texts: How do I correctly multiply an XMMATRIX by a scalar?

texts:
Using DirectXMath and its XMMATRIX structure in C++ and Direct X 11, how does one multiply that matrix structure by a single float scalar?

I want to implement the operation B = A * f; where A and B are XMMATRIX and f is a float.

I found all sorts of functions to multiply a matrix by another matrix or a vector. I found all sorts of functions to construct matrices.

I could find no scalar multiplication! Why is there no such function? Is there no use case? Did I miss something? How do I implement scalar multiplication?


texts: Mental Image of the engine behind an RTS like SimCity/Settlers, what is it?

texts:
Disclaimer: I'm first a programmer and then an RTS gamer. This means I'm a complete and utter newb in terms of patterns, best practices and glossary of technical terms on the game dev world.

Since I was a kid that most of my electric/electronic toys were always taken apart to learn how they were made and most of the pieces were stored for future use.
This gave me a VERY curious mind in terms of: How does it work?

I've started planning/scribbling for more RTS games than the market has dished out, but never got around to implement any of them due to the lack of basic knowledge about Game Devel.

So what I'm asking is that someone could point me in the direction of the engine schematics of an RTS game like SimCity/Civ/Settlers. Something that will assume a bit of programming background but will introduce the terms used for programming a RTS base game.

How do they do the Unit Manager? Is it called this way?
Is creating a complex multi threading system wise?
Should I use multi-threading just for groups of units?

Well, I think you get the picture of how newb I am ;)

Many thanks in advance.


texts: Android Density Independent Pixel Drawables Resource Folder

texts:
I'm trying to get to grips with DIP in Android (using Eclipse). I'm writing a little game with OpenGL ES 2.0. Could I get some guidance and tips on what I'm not understanding/doing right.

From what I understand I need to make different sizes of the same image so that they appear correctly on different devices. This is because each device has a different aspect ratio and a 1cm by 1cm sprite on one screen might not be 1cm by cm on another screen.

I read here that I need to place my sprite images in the res/drawables folders. I did this, but when I try to reference the resource using:

    mySpriteTexture = new Texture(context, R.mysprite);

the R class fails to find the .png. I have tried cleaning, rebuilding etc., and tried variations like R.res.mysprite. Although I don't see the point in trying R.res.drawables-XXX as according to the article Android is meant to pick the correct images on running...

I think it must be something to do with the XML manifest? But I have no clue. Any help would be welcome.


texts: Is there any performance benefit to sharing shaders between programs?

texts: OpenGL allows you to share the same shader between multiple programs. Aside from saving small amounts of memory and a shader handle, are there any GPU-side performance benefits to doing this?


texts: How do I calculate market share in an economic simulation?

texts:
I want to make a game in which the players create different products (supply), and I give them a certain finite number of customers (demand). Players can choose the price and quality of their products (among perhaps other variables).

I've been trying to come up with an algorithm to decide on the market share of each product based on those variables. I could do something random, but thought I'd ask first!


texts: Object to reach height depending on its gravity and mass

texts:
A mathematician will probably think this was a silly question, but I'm not one and I'm in need of help :D
I'm working in Godot and with its RigidBody2Ds (objects that have automated physics behaviour).
I want to create a spring of type RigidBody2D (the 'springiness' is not the only function of this object).
I'm at the point in code where this spring and another RigidBody2D collide so I have all information about the two bodies at the moment of collision.
My goal is to make any body that touches the spring reach a certain height (from the spring), and move by certain speed horizontally, as you can see in the picture

So, the information about both bodies I have is: position, velocity, gravity scale, mass, weight.
What I want to achieve is constant line of movement of any object (that may have different properties I mentioned above) by applying a certain force to the colliding object.
I can stop the body before applying new force to it, that is, at the time of collision.
Rotation, friction, absorption and similar properties don't need to be counted on as the game I'm making is a simple one. With this I'm trying to make a predictable movement for the player to count on. I also plan to disable collision briefly at the time of collision so that the colliding object can touch the spring from any angle and the collision result would be the same.
EDIT:
Here's some of my testing
Stones have random mass from 1 to 50, in this case 45.748413, 41.445225, 24.259401 and 37.189552 and all have same gravity scale (GS), that is: 2.
The slime has GS of 5 and mass of 1.
I bothered to make a seamless gif, so you can only see the two jumps here. Because the spring has circular shape they fall apart after i think 10 bounces.

From this test I see that mass doesn't matter when I use @Sergio's method, so that's a step foreward. Thanks @Sergio!
func _on_body_entered(body):
    if body is RigidBody2D:
        body.set_linear_velocity(Vector2(0, -50 * body.gravity_scale))

Now, even though they don't reach the same height, they have same timing - from first touching the spring (yeah, i know, it doesn't look like a spring), to falling back. So that's also a step foreward, but I still don't have an idea how to get them all to get to the same height.


texts: MonoGame - Scale Texture2D from 16x16 to 64x64

texts:
I need to scale a Texture2D (let's say it's 16x16) to 64x64.

I tried scaling it in the SpriteBatch#Draw method, but it doesn't look like pixel art as soon as it's drawn, more like a lot of anti-aliasing happened.

I chose 64x64 because 16x16 is pretty small, and I thought I could just scale every pixel by 4 (1x1 pixel in 16x16 could be 4x4 pixels in 64x64), basically I don't want MonoGame to anti-alias when I draw the scaled Texture.

Thank you!


texts:
Many game engines I've seen which are based on an Entity Component System. It has some kind of a Transform Component as a necessary component attached to all of their entities. While this does seem to make kind of sense considering an entity is only some kind of property bag and a collection of components and transformations are world space behavior (hence just part of the composition). I've noticed two other things which are very weird:

Transform components are used to build up the hierarchy between entities as they have a parent entity as well as child entities
Transform components are specialized for only a single kind of world space, e.g. 2D or 3D.

Examples:

The Unity3D engine. Entity children and parents seem to be accessed through the Transform Component of each entity. Also, the Transform Component features coordinates in 3D vectors.
The Xenko Game Engine (previously Paradox3D), which can bee seen on GitHub.

So, is this a common practice? Best/worst practice? What's the reason behind having:

a fixed Transform component,
making the Transform component only suitable for one world space
using the Transform component as an hierarchy graph?


texts: Is there documentation on XNA other than at MSDN?

texts: MSDN documentation of XNA seems to be incomplete and/or bad. Is there another resource available? And by documentation I mean of the library/framework itself, similar to what UNITY, SFML, or SDL all have available.


texts: How to make Flood fill algorithm return different Lists of separate groups in the grid?

texts:
So i have this flood fill method :

 public int groupedCells(int y, int x, int value)
{
    //base state
    if (!gSetup.isValidLocation(y, x) ||
        gSetup.getCell(y, x).value != value ||
        gSetup.getCell(y, x).cMAtch.isInMatchPool)
    {
        return 0;
    }

    // keep track of matched cells
    gSetup.getCell(y, x).cMAtch.isInMatchPool = true;

    // collect
    int up = groupedCells(y + 1, x, value);  //  up
    int left = groupedCells(y, x - 1, value);  //  left
    int right = groupedCells(y, x + 1, value);  //  right
    int down = groupedCells(y - 1, x, value);  //  down

    // sum
    int total = up + left + right + down + 1;

    return total;
}

basically i have this grid :

and currently if i click on a yellow triangle, the method above will tell me how many of them are next to each other.

What i want is a solution that will run all over the grid, and check if a group has :

less than 3-triangles then do (A)
if it has 3-triangles then do (B)
if it has 4-triangles then do (C)

etc ...

Am not sure about this, but i thought the best way is to have a list for every group, and then check those conditions over the lists.

I tried it here but the list keep re-initializing itself, so it always either have 0 cells or 1 :

  public List<CellSetup> listedCells(int y, int x, int value)
{
    List<CellSetup> cList = new List<CellSetup>();
    //base state
    if (!gSetup.isValidLocation(y, x) ||
        gSetup.getCell(y, x).value != value ||
        gSetup.getCell(y, x).cMAtch.isInMatchPool)
    {
        return cList;
    }

    // keep track of matched cells
    gSetup.getCell(y, x).cMAtch.isInMatchPool = true;
    cList.Add(gSetup.getCell(y, x));
    // collect
    List<CellSetup> up = listedCells(y + 1, x, value);  //  up
    List<CellSetup> left = listedCells(y, x - 1, value);  //  left
    List<CellSetup> right = listedCells(y, x + 1, value);  //  right
    List<CellSetup> down = listedCells(y - 1, x, value);  //  down

    return cList;
}

The result of that method when its called here :

for (int y = 0; y < gSetup.cell2DArray.GetLength(0); y++)
        {
            for (int x = 0; x < gSetup.cell2DArray.GetLength(1); x++)
            {

                print(listedCells(y, x, 1).Count);
            }
        }

is printing "1" three times and "0" 22 times.

Thank you


texts: SFML.NET DLLNotFoundException with dll.config files in project

texts:
I am trying to run SFML.NET on arch linux and I have two dll.config files in my project called sfmlnet-graphics-2.dll.config and sfmlnet-window-2.dll.config.

sfmlnet-graphics-2.dll.config:

    <configuration>
       <dllmap os="linux" dll="csfml-graphics-2" target="libcsfml-graphics.so" />
       <dllmap os="linux" dll="csfml-window-2" target="libcsfml-window.so" />
    </configuration>

And sfmlnet-window-2.dll.config:

    <configuration>
       <dllmap os="linux" dll="csfml-window-2" target="libcsfml-window.so"/>
    </configuration>

So the dll map should work, though I still get this error when I try to run.

    Unhandled Exception: System.DllNotFoundException: Unable to load DLL
    'csfml-graphics-2': The specified module or one of its dependencies
    could not be found.
     (Exception from HRESULT: 0x8007007E)
       at SFML.Graphics.RenderWindow.sfRenderWindow_createUnicode(VideoMode
    Mode, IntPtr Title, Styles Style, ContextSettings& Params)
       at SFML.Graphics.RenderWindow..ctor(VideoMode mode, String title,
    Styles style, ContextSettings settings)
      at SFML.Graphics.RenderWindow..ctor(VideoMode mode, String title)
      at HelloSharp.Program.Main(String[] args) in
   /home/kas/Documents/CodeProjects/HelloSharp/Program.cs:line 13

This is my Program.cs file:

    using System;
    using SFML.Graphics;
    using SFML.Window;

    namespace HelloSharp
    {
        class Program
{

    private static RenderWindow window;
    static void Main(string[] args)
    {
        window = new RenderWindow(new VideoMode(1280, 720), "Game");
        window.Closed += new EventHandler(OnClosed);
        window.KeyPressed += new EventHandler<KeyEventArgs>(OnKeyPressed);

        while(window.IsOpen) {
            window.DispatchEvents();
            window.Clear();
            window.Display();
        }
    }

    private static void OnKeyPressed(object sender, KeyEventArgs e)
    {
        RenderWindow window = (RenderWindow) sender;
        if(e.Code == Keyboard.Key.Escape)
            window.Close();
    }

    private static void OnClosed(object sender, EventArgs e)
    {
        RenderWindow window = (RenderWindow) sender;
        window.Close();
    }
}
    }

Here is a picture of my projects layout (where all the files are in relation to each other).

I have the linux version of the csfml .dll's next to the project dll, as well as the linux .so files and the sfmlnet .dll's. I went through a bunch of google searches, tried a bunch of fixes and nothing seems to work. If you take the time to try and help me I appreciate it.
~Kas


texts:
I am fairly new to unity and I have encountered this same problem previously.

I have a gun with hands and I created an animation that simulates shot movements with properties transform.position and transform.rotation. Root motion is applied and motion curves are generated for the animation.The default state animation for that object has no properties assigned to it and as much as I understand from the animation controller window, the shot animation is completed before the transition to the default state is made.

The problem is that on every 3 shots 0.001 is added to the X rotation; Y and Z positions are losing some small values.

I tried to prolong the animations exit time but the result is the same. I checked the key values and the motion curves, the first and last ones are the same. Why is this happening and how can I fix it ?


texts: How to draw the elements that are in a Texture2D list in XNA

texts:
I have a Texture2D list called blockTexture that has 2 elements in it.

I use the following line to draw the first element.

foreach (Vector2 blockPosition in blockPositions)
for (int i = 0; i < blockPositions.Count; i++)
{
 spriteBatch.Draw(blockTexture[i], blockPositions[i], Color.White);
}

This allows me to draw the elements in different positions. However, while I run it after like 3-4 seconds it gives OutOfRangeArgument error.

I was wondering what am I doing wrong or is there another way to do this.
I'm really sorry if my question sounds stupid but I'm a total beginner.

PS: this is a game where different type of objects fall from the top of the screen to the bottom, and the person at the bottom needs to avoid some of the objects and try to catch the others.

List<Vector2> blockPositions = new List<Vector2>();
List<Texture2D> blockTexture = new List<Texture2D>();

These are in the load content

blockTexture.Add(Content.Load<Texture2D>("Block"));
blockTexture.Add(Content.Load<Texture2D>("right"));

These are in the update section

for (int i = 0; i < blockPositions.Count; i++)
 {
  // Animate this block falling
  blockPositions[i] =
  new Vector2(blockPositions[i].X, blockPositions[i].Y + BlockFallSpeed);

  // Get the bounding rectangle of this block
  Rectangle sprite =
  new Rectangle((int)blockPositions[i].X, (int)blockPositions[i].Y,
                    blockTexture[0].Width, blockTexture[0].Height);

  // check collision with person
  if (personRectangle.Intersects(sprite))
   personHit = true;

  // Remove this block if it have fallen off the screen
   if ((blockPositions[i].Y > Window.ClientBounds.Height))
   {
    blockPositions.RemoveAt(i);
   // When removing a block, the next block will have the same index
   // as the current block. Decrement i to prevent skipping a block.
    i--;
    }
  }

  base.Update(gameTime);

}


texts: How can I add to the text multiple words or numbers?

texts:
Now I'm using {0} I add anywhere in the text in the editor {0} and it will add the random number or random word. But I want now to be able to add for example also {1} and {2} so if for example the array of words is: hello,hi,bye and I will make in the editor in the text {0}……{1} it will add randomly two words from the array like hello and hi or hi and bye. It will pick up two random words. I don't place the {0} and {1} in same place each one in other place in the text and each time it will pick two random words and will display one word at {0} and one at {1}

Same for the numbers.

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

public class CustomText : MonoBehaviour
{
    public Text textField;
    public Vector2 randomRangeHours;
    public string[] words;
    public bool randomWords = false;

    private string defaultValue;
    private string originalValue;

    public void Init()
    {
        defaultValue = textField.text;
        originalValue = textField.text;
        GenerateRandomHour();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GenerateRandomHour();
        }
    }

    private void GenerateRandomHour()
    {
        string word = "";
        if (words.Length > 0)
        {
            word = words[UnityEngine.Random.Range(1, words.Length)];
        }

        string numberName = UnityEngine.Random.Range((int)randomRangeHours.x, (int)randomRangeHours.y).ToString();

        int t = Int32.Parse(numberName);
        if (t == 1)
        {
            defaultValue = defaultValue.Replace("hours", "hour");
        }
        else
        {
            defaultValue = originalValue;
        }

        if (randomWords)
        {
            textField.text = string.Format(defaultValue, word);
        }
        else
        {
            textField.text = string.Format(defaultValue, numberName);
        }
    }
}


texts:
I'm making a car game and doing the dashboard part. I'm trying to do the dashboard lights, i've did this changing the dashboard texture, overwriting the texture with the light image over it, example:

Texture2D dashboardTexture;
Texture2D parkingBrakeLightTexture;
Model carModel;

//when the light needs to turn on:

PutTextureOverDashboardTexture(parkingBrakeLightTexture);

//on Draw method I change the texture of dashboard mesh:

effect.Texture = dashboardTexture;
effect...

This is alright, but the lights will suffer influence from the external light if I EnableDefaultLighting() in the effect, then the dashboard lights will almost don't appear depending on what direction the car is, and of course that should not happen.
So how can I make the lights of dashboard appear? I need to use another alternative? Or can I still utilize this method?


texts:
The Aves game engine made a splash last spring/summer, with very impressive demo videos. I went back to check on them, and it looks like their site has long since died. Google also doesn't seem to know anything new about them.

Where can I find news about Aves? Is the project dead?


texts: Detecting collision on a grid with a fast-moving object

texts:
I am working in a 2D collision system where I need to detect a collision of a rectangle on a grid, but since the rectangle may be fast enough to jump more than one of the grid squares (sometimes several) I need to check collision of everything in the middle of point A to B.

Does anyone know a way to achieve that?

In the image below, I am starting at point A and in one update it's at point B. I would need to check collision on the whole gray area. As you can see in the image, the rectangle don't need to be on a fixed position on the grid.

The grid squares in my case have 30x30 pixels and the rectangle has 35x65. My grid is also on a list, but this can change if needed.

Thank you in advance for any help.


texts: Implementing an enum from an abstract class

texts: Both my Player class and Enemy class should have an enum called State. (The values inside of that enum would be different in each class.) I'd like to have the Player class and Enemy class inherit from an abstract base class that would require those two classes to have that enum. Is this possible?


texts: Maintaining facing direction at the end of a movement

texts:
I want to make my 2D top-down walking animation stop and revert to the idle animation while continuing to face in the same direction as the previous movement.
For example, when I go up then stop, my character should continue to look up. If I go down, it should continue to look down.
I use lastmoveX and lastmoveY floats for idle and for walking I use moveX and moveY floats. moveX and moveY change when I move with the joystick, but lastmoveX and lastmoveY do not change, and I don't know how to fix this.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D myRB;
    private Animator myAnim;
    public Joystick joystick;
    public MoveByTouch controller;

    [SerializeField]
    private float speed;

    // Use this for initialization
    void Start ()
    {
        myRB = GetComponent<Rigidbody2D>();
        myAnim = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update ()
    {
        myRB.velocity = new Vector2(joystick.Horizontal, joystick.Vertical) * speed * Time.deltaTime;

        myAnim.SetFloat("moveX", myRB.velocity.x);
        myAnim.SetFloat("moveY", myRB.velocity.y);

        if(joystick.Horizontal == 1 || joystick.Horizontal == -1 || joystick.Vertical == 1 || joystick.Vertical == -1)
        {
            myAnim.SetFloat("lastMoveX", joystick.Horizontal);
            myAnim.SetFloat("lastMoveY", joystick.Vertical);
        }

    }
}


texts: Quaternion Rotation - Clockwise or Counter-Clockwise?

texts:
when we specify a Quaternion as (axis of rotation, rotation amount), in which 'direction' is the rotation, assuming we are looking down the rotation axis (i.e. camera at the origin, looking along the axis vector)?

Does it depend on the handed-ness of the co-ordinate system?

Or is it actually a moot point / stupid question?


texts: How do I efficiently use 16 bit texture coordinates?

texts:
While loading a model I get a big array of 32 bit floating point texture coordinates. I just upload that to a single vertex buffer (along with other data, such as vertices, normals, etc.) and use it while rendering via

glVertexAttribPointer(texcoordindex,2,GL_FLOAT,GL_FALSE,texcoordstride,texcoordoffset);

I use this format for all types of meshes.

However, 16 bit and the ~65000 possible values are more than enough to represent textures that are mostly smaller than 4096 in size per dimension.

Now I'm wondering how to most effectively switch to some 16 bit based texture coordinate format, with respect to maximizing performance, i.e. minimizing the bandwidth and storage used, as well as minimizing ALU operations. Mainly I'm wondering:

Should I use half floats or short integers?
How do I convert the 32 bit floats I get when loading the model safely to the respective 16 bit format and upload it to the vertex buffer? In C++ or other languages, by rolling some custom type conversion via bit twiddling, or use standard procedures provided by the language or libraries such as GLM?
How do I have to change the glVertexAttribPointer call to use that format, and does the input in the vertex shader stay a "vec2"?
Is there maybe another option to save space here? For example, most textures are in the range of 256x256 to 1024x1024 range. 16 bits are way too much for that, but 8 bit are not enough for most textures. Are there some other strategies to save space here?


texts:
I have this annoying window in the bottom right of the scene view.  From the manual, it seems like I opened it by clicking on the wrench & scribe button next to the movement buttons.

How do I make it do away now?

Restarting doesn't make a difference, neither does creating a brand new project.

The documentation say this appears it I've clicked on the tools icon and there aren't any custom tools (which I'm sure I have done).  Surely is should vanish after a while though.


texts: How to create a legally valid timestamp of unpublished game artwork

texts:
Before publishing promotional material of my first indie game I wanted to mark all my artwork with a legally valid timestamp.

There are two ways I know to do this:

 1 go to a sollecitor/lawyer and pay for them to certify the document
 2 use an online webservice to mark any given file/folder readable to the service

Anyone has already done this and if yes how (e.g. which website have you used? which type of solecitor have you contacted? etc..)?

I am doing all this because I have prepared a kickstarter video that I wanted to publish in these days to ask for some additional funds to complete my game and, as it contains sequences of the game, I am at the same time worried about publishing it (somebody might copy the characters as I say in the video that I would like to do also a comic book series based on those characters). I guess that "eCO" (or something similar) becomes a must in this case right?

Kind Regards

PS: I know that there is always the good old "send yourself a mail with a stamp and a date" but is not very strong as proof.


texts:
I want to license my game, to protect my intellectual property, but I also want to make it open-source, and sell it.

I have an engine that I'd like to open-source, but I'd like to be the only one with rights to distribute it in that form. I'd like people to be able to distribute it however they wish, if it is their modified version. I'd like games made with the engine to be able to be sold, but not re-distribute the engine, and they must credit it if they do use it.

I'm not a legal expert, and I have no experience as of yet with licensing. Which licenses will allow me to do this?


texts: How do I make a 2D sprite flash green when tapped?

texts: I have a sprite that is based on an image of a gray circle. When the user touches the sprite, I want the sprite to flash green, as in I want the circle to appear to turn green for 0.2 seconds. I tried setting the color of the sprite via SpriteRenderer's function SetColor, and it blended the color with the initial gray color of the sprite, so I got a very dark green even though I'm really sure I didn't mess up the values when I created the color. Now I'm trying to get my flashing effect by using separate images. I have the images I need, and I have a message getting logged when I tap the circle, I just need to setup a non-looping animation and trigger that animation in my code.


texts: Is it possible to use a spherical collision component in UDK?

texts:
I have an object in UDK, which has a SkeletalMesh. At certain times in the game, I want this object to continue rendering the SkeletalMesh, but I'd like it to use spherical collision temporarily.

After reading a bunch about PrimitiveComponents, my understanding is that UDK supports cylindrical and box-like collision, but not spherical without using a static mesh.

EDIT:
What I have now is a StaticMesh with a material that makes it invisible. I've added a StaticMeshComponent to my Pawns. I can shut off the Pawn's collision, and turn on the StaticMesh collision. But it doesn't respond to impulses. I figure I'm missing something in how you turn on the RigidBody thingy.

CylinderComponent.SetActorCollision(false, false);
SetPhysics(PHYS_RigidBody);
RBCollisionComponent.SetStaticMesh(RBCollisionMesh);
RBCollisionComponent.AddImpulse(InImpulse);
RBCollisionComponent.WakeRigidBody();


texts: Lately I wondered, which draw command is faster, drawArrays or drawElements. I know difference between them, drawArrays just draws every vertex in the same order they were provided, and drawElements draws vertices based on the provided indices. But I'm still curious which command is faster, or when should I use drawArrays instead of drawElements and vice-versa.


texts: How do I predict ball movement, after collision, in game of pool?

texts:
I'm trying to draw lines that predict the movement after collision between two balls, in a game of pool. How do I do that?

I heard it can be done via raycasts, but how do I draw a line?


texts:
I did a simple pixel shader that makes the texture monochrome, and it works perfectly when it is precompiled, but not when compiled (returns E_FAIL).
The effect was compiled using fxc.exe with these arguments: fxc /T ps_2_0 /Fo BasicHLSL.fxc BasicHLSL.hlsl

Here's the code

ID3DXEffect* monochromeShader = nullptr;

void initEffects(GameWindow& w)
{
    long errorID =
    D3DXCreateEffectFromFile
    (
        w.getD3DDevice(),
        "data/shaders/BasicHLSL.fxc\0",
        NULL,
        NULL,
        D3DXFX_NOT_CLONEABLE,
        NULL,
        &monochromeShader,
        NULL
    );

    std::cout << std::hex << errorID;

    if (monochromeShader == nullptr)
        showErrorMsg(std::to_string(errorID).c_str());
}

And here's my shader before compiling with fxc.exe:

// Pixel shader input structure
struct PS_INPUT
{
    float4 Position   : POSITION;
    float2 Texture    : TEXCOORD0;
};

// Pixel shader output structure
struct PS_OUTPUT
{
    float4 Color   : COLOR0;
};

// Global variables
sampler2D Tex0;

PS_OUTPUT ps_main( in PS_INPUT In )
{
    // Output pixel
    PS_OUTPUT Out;

    Out.Color = tex2D(Tex0, In.Texture);
    float4 f4 = Out.Color * float4(0.299f, 0.587f, 0.114f, 1.0f);
    float f = f4.r + f4.g + f4.b;
    Out.Color.rgb = f;

    return Out;
}

// Effect technique
technique tech_main
{
    pass P0
    {
        // shaders
        VertexShader = NULL;
        PixelShader  = compile ps_2_a ps_main();
    }
}

Thanks for reading.


texts:
I've searched and searched for a solution today but haven't found one.

I have a Camera with Vector3 and also the camera has an angle.

If I use this:

hero.position.x += speedX;
hero.position.z += speedZ;

works great but as soon as I rotate the camera the "hero" still goes in the same direction. So if I press button W I want the hero to go the way the camera is looking.

I've also tried:

hero.position.x += Math.sin(hero.rotation*3.1415/180) * speedX;
hero.position.z += Math.cos(hero.rotation*3.1415/180) * speedZ;

But it wont work and I just can walk in a line.

So how do I move in 3D space in first person mode?


texts:
Im currently trying to create a game where you visit planets in LibGDX for Java. To do this I use a TiledMap which is basically just an array of tiles to represent the planets themselves. To get the necessary curvature, I use a Shader; it works by assigning an angle to every vertex and placing it according to the camera position. It looks like this:

I now use a shadowmap to get lighting into the game. This is done by drawing shades of grey onto a texture and strechting the texture over the gameplay after that (specifically a FrameBuffer). Without any shaders it looks like this: .

My problem now is to turn the shadowmap into a planetlike shape (circular shape). You now have to use a fragment shader, but I dont really know the method. If you have an idea that might solve this problem, just post it. I've been working on this for a few weeks now and haven't made much progress.

If you want to know what idea I had take a look at this:

This is the fragment shader I tried to use to render the shadowmap, it resulted in . As you can see its got a basic circular form, but is kinda distorted (I know the problem arises out of how the angles are used, but Im not sure how to fix it yet). This is how the texture is represented in the shader (with uv): http://i.imgur.com/pTQp8AJ.png

precision highp float;

uniform sampler2D u_texture;

uniform float TEXTURE_WIDTH;
uniform float TEXTURE_HEIGHT;
uniform float VIEWPORT_WIDTH;
uniform float VIEWPORT_HEIGHT;
uniform float CAM_X;
uniform float CAM_Y;

varying vec2 uv;
varying vec4 v_color;

void main() {

    // THE RATIO OF TEXTURE WIDTH TO TEXTURE_HEIGHT WHICH YOU MULTIPLY WITH UV.X TO NOT ALLOW STRETCHING
    // (LOOK AT HOW THE TEXTURE IS REPRESENTED TO UNDERSTAND)
    float k = TEXTURE_WIDTH / TEXTURE_HEIGHT;
    uv.x *= k;

    // THE CENTER OF THE PLANET RELATIVE TO TEXTURE_HEIGHT AS 1
    vec2 m;
    m.x = (k * VIEWPORT_WIDTH) / (2.0 * TEXTURE_WIDTH);
    m.y = - ((CAM_Y - 0.5 * VIEWPORT_HEIGHT) / TEXTURE_HEIGHT);

    // THE DISTANCE FROM CURRENT UV COORDINATE TO CENTER
    float d = distance(uv, m);

    // THE RANGE OF ANGLES
    float a = abs(atan(m.x/m.y)) * 2.0;

    // THE ANGLE OF THE CURRENT UV COORDINATE
    // + THE LEFTOFER ANGLE FROM HOW MUCH THE PLAYER HAS MOVED FROM THE CLOSEST INTEGER POSITION
    float angle = atan((uv.x - m.x)/(uv.y - m.y)) + (CAM_X - floor(CAM_X)) * (a / VIEWPORT_WIDTH);

    // ASIGN THE DISTANCE AND ANGLE TO ONE POINT IN THE TEXTURE
    uv.x = ((angle + 0.5 * a) / a)*(VIEWPORT_WIDTH / TEXTURE_WIDTH);
    uv.y = d + m.y;

    // GET THE COLOR OF THE TEXTURE AT THIS POINT
    vec4 color = texture2D(u_texture, uv) * v_color;
    gl_FragColor = color;
}


texts: Implementing Turn based Combat Using Node js

texts:
I am creating a browser game that allows players to fight monsters using Nodejs, Socket.io and Express. However I can't seem to figure out how to implement the turns of combat.

My train of thought and workflow is as follows:

The player declares an attack on a monster (Client makes a Post request.) -
Working
The server get's the player's stats as well as the monster's. - Working
The player selects his action and attacks, then it's the monster's turn and so on. - Can't figure this out

How would such a functionality be implemented?


texts: How to get the overlap volume of OBB and or ABB?

texts:
The following code is a current attempt at a function I have to determine if two bounding boxes overlap. The bounding box structures are [min[x,y,z], max[x,y,z]] The following .gif shows the current undesired behavior.

aabbOverlap(otherWorldAABB){
  // copied from
  // http://blog.meltinglogic.com/2015/04/aabb-overlapping-area/
  // Vector3 min = Vector3(max(min1.x, min2.x), max(min1.y, min2.y), max(min1.z, min2.z));
  // Vector3 max = Vector3(min(max1.x, max2.x), min(max1.y, max2.y), min(max1.z, max2.z))

  return [
    [
      Math.max(this.worldAABB[0][0], otherWorldAABB[0][0]),
      Math.max(this.worldAABB[0][1], otherWorldAABB[0][1]),
      Math.max(this.worldAABB[0][2], otherWorldAABB[0][2]),
    ],

    [
      Math.min(this.worldAABB[1][0], otherWorldAABB[1][0]),
      Math.min(this.worldAABB[1][1], otherWorldAABB[1][1]),
      Math.min(this.worldAABB[1][2], otherWorldAABB[1][2]),
    ]
  ]
}

The gif has a render of the two entities bounding boxes the house and robot they are rendered in pink and then green when they overlap. Then I try to render the verts and the volume for the overlap section in White. You can see in the gif that some of the verts are way off from what you would expect and the volume gets skewed

Why I need this

I am using the AABB collision as the broad phase of my detection test. I want to calculate the overlap to restrict the narrow phase algorithim to within that overlap space. The narrow phase pass i'm using is a swept-sphere-to-triangle detection. I want to limit the mount of triangles scanned to within the overlap.


texts:
I am currently trying to implement a specific directional light type.

This light type has been used in the game INSIDE and is called orthogonal spotlight (aka local directional light). I assume that this is a directional light which behaves like a spot light and have a squared or rectangular attenuation but I have some difficulties to integrate it in my deferred pipeline and get the general concept of this light type.

Implementing a simple directional light is simple dot(worldNormal, lightDir) but what kind of data should I use to constraint its application into a square or a rectangle ?

I hope that you'll be able to give me some clues. Thanks a lot !


texts: Unity - how to remove standard sky but keep the lighting?

texts: How can I remove the standard Unity sky (to have an empty space with no texture around my scene), but keep all the lighting effects from it?


texts: GL_EXT_shadow_samplers killing my shader

texts:
I have the following fragment shader for my scene

#extension GL_EXT_shadow_samplers : require
...
vec4 color = texture2D(uTextureUnit0, varTexCoord0);

if (colorTransformEnabled != 0) {
    vec3 transformedColor = colorTransform * color.rgb;
    color = vec4(transformedColor, color.a);
}
gl_FragColor = color;

this works like expected.

Now I add this line:

float shadow = shadow2DProjEXT(uShadowTexture, varShadowCoord);

and boom my shader does not produce any output at all.
GL_COMPILE_STATUS and GL_LINK_STATUS do not return any error messages. Any idea where to go from here to debug this?

Edit:

I'm on iOS and GL_EXT_shadow_samplers is supported.

Edit:

I forgot to check for error at some point. Now I get a GL_INVALID_OPERATION on glDrawElements. Any idea what could cause this problem? Since I do not get the error when I don't use the shadow2D functions.

Edit:

The following state change overview might help some more:

Where GL_TEXTURE0+1 is the depth texture and GL_TEXTURE0 is the objects texturea

Edit:

I found out that it produces the error as soon as the shader contains a call to shadow2DProj the invalid operation error is thrown. Although the shadow2DProj function is never called in the shader. And it still throws the error if shadow2DProj is called.