texts: How to implement a component based system for items in a web game

texts:
Reading several other questions and answers on using a component based system to define items I want to use one for the items and spells in a web game written in PHP. I'm just stuck on the implementation.

I'm going to use a DB schema suggested in this series (part 5 describes the schema);
http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/

This means I'll have an items table with generic item properties, a table listing all of the components for an item and finally records in each component table used to make up the item.

Assuming I can select the first two together in a single query, I'm still going to do N queries for each component type. I'm kind of fine with this because I can cache the data into memcache and check there first before doing any queries. I'll need to build up the items on every request they are used in so the implementation needs to be on the lean side even if they're pulled from memcache.

But right there is where I feel confident about implementing a component system for my items ends. I figure I'd need to bring attributes and behaviors into the container from each component it uses. I'm just not sure how to do that effectively and not end up writing a lot of specialized code to deal with each component.

For example an AttackComponent might need to know how to filter targets inside of a battle context and also maybe provide an attack behavior. That same item might also have a UsableComponent which allows the item to be used and apply some effect onto a different set of targets filtered differently from the same battle context. Then not every part of an item is an active part, an AttributeBonusComponent might need to only kick in when the item is in an equipped state or when displaying the item details page.

Ultimately, how should I bring all of the components together into the container so when I use an item as a weapon I get the correct list of targets? Know when a weapon can also be used as an item? Or to apply the bonuses the item provides to a character object?

I feel like I've gone too far down the rabbit hole and I can't grasp onto the simple solution in front of me. (If that makes any sense at all.)

Likewise if I were to implement the best answer from here I feel like I'd have a lot of the same questions.
How to model multiple "uses" (e.g. weapon) for usable-inventory/object/items (e.g. katana) within a relational database


texts: C++ alternative to vector for arbitrary number of objects using pointers

texts:
I'm working on a prototype 'life simulation' game which incorporates any number of objects / entities that may exist in the game.

Up until this point I had been working with vectors of the objects, with every object that gets instantiated gets automatically copied into a vector that allows for some very simple all encompassing functions like:

physics_manager()
{
    for(std::size_t i = 0; i < all_objects.size(); i++)
        all_objects[i].do_physics();
}

However, I've run into a problem when it comes to using pointers. Previously I used  pointers to elements within vectors to interact with objects like this:

class object
{
    //Attributes of object
    object * other_object_to_interact_with;
    std::vector<object*> carried_objects
    //etc
}

I've now realised that changing the size of the vector (a frequent occurrence in this simulation) causes all pointers to elements within that vector to point to some random piece of memory.

I've considered using some form of unique ID for this (e.g. an int assigned to each object, then searching the vector for an object with that int to identify the right one), but this feels like an inefficient and ultimately wrong way to do things.

My question is, is there a container similar to the std::vector that:
a) can be iterated through easily for functions such as the above
b) can hold an arbitrary number of objects that changes during program running
c) is safe to use pointers to elements within it even if the container changes size

Alternatively, is there a way to use vectors to achieve the above without using pointers?

UPDATE: An additional thought - would the issue below be present if instead of vectors containing actual objects, I used vectors containing pointers to objects? Presumably then any pointers to objects outside of the vector would be to the objects themselves - how well would C++ memory manage this or would this lead me into new / delete territory?

FURTHER UPDATE: I migrated to lists rather than vectors, which was surprisingly easy. My most commonly used code snippet was:

for(std::size_t i = 0; i < vector.size(); i++)

This was very easily changed to:

for(auto & i : list)

With 'i'  now pointing to an actual object of the list rather than an int that can be used to access the vector with vector[i]. No perceptible performance hit so far with approximately 20000 objects being iterated through.

Additionally, when there is a need to use an 'int' as a reference to one of the objects within the list, that's as simple as:

int j = 0;
for(auto & i : base_class_vector)
{
    if(j == desired_number)
    {
        //Do whatever's needed here
        break;
    }

    j++;
}


texts: How do I make my turn based battle system scalable?

texts:
I’m currently working on a turn based battle system for my game. The game is in unity coded with c#.
The turns are based off of an initiative system determined by each characters speed. Right now I have a turn manager that got a queue of all the characters. Then to increment the turns I enqueue the current active character, then dequeue and set them as active.
All of the tutorials I see online use an enum to make a basic battle state system. I am thinking about implementing this next but I am wondering if this is the best approach or if there is different systems that are more scalable.


texts: Assigning jobs to in-game entities to carry out tasks (move object, build item etc.)

texts:
I'm not really sure what to call this so I'm struggling to Google for solutions.

Basically my game will have resources (wood, stone, etc) that are "delivered" to a point on the map. I want worker entities to collect resources and deliver them to where they need to be (a building site or put them in storage).

My problem is that I don't know how to structure this kind of "job queue".

My first idea was that when a resource is delivered it creates a "job" object in a queue. Then in the game cycle I'll find all workers that are idle, pop the next job off the stack and assign it to him.

Am I heading down the right path? Is there a better way of doing this? Can someone tell me what I should be Googling to find examples of what I'm trying to achieve?


texts: How to attach a sprite to a TMXTiledMap at a particular coordinate, in AndEngine?

texts:
I am trying to add a sprite at a "grid" location on the tiled map. The TMX tiled Map is like a grid, and you can access the size of the grid by calling mTMXtiledMap.getTileRows() and mTMXtiledMap.getTileColumns().

I want to add an object at grid location, say (2, 5). My tileMap is of size (10,10).

How can I do that? There is no function like mTMXTiledMap.addChild(int x, int y, Entity mEntity).

I would appreciate any suggestions!


texts: How can I implement a game locator or proxy server?

texts:
I have a turn-based strategy game which already has a multiplayer server/client layer that works fine on local network (where one server is set up and players connect to it).

I would like to extend this architecture to allow players to play via Internet, but I don't want to have a dedicated game server for that, especially due to performance issues. The game's AI is runs on the game server of course, and multiple games with computer players would "kill" the machine.

I would like to have some kind of "central connection point" server that does not run the game logic, state or AI but can be used by players to find servers hosted by other players. How can I implement this?


texts:
The way that I create shadows is by the following technique:
http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/

But I have questions to HLSL. The way that I currently do it is, I have a black and white image, where Black means 'object', and white means 'nothing'. I then distort the image like in the tutorial. I do this with a pixel shader, but instead of rendering to the screen, I render to a texture, back to my application. I then take this, and create the shadows, and then send it back to the graphics card to undo the distortion, after the shadow has been added - this comes back and I have a stencil of shadow. I can put this ontop of the original image and send them back to the graphics card, which then puts them on the screen.

To me this is alot of back and forth. Is there a way i can avoid this?

The problem that I am having is that I need to basically go through all positions in the texture 3 times, and use the new new texture every time instead of the orginal one. I tried to read up on Passes, but i don't think that i am heading in the right direction there.

Help?


texts: Can glsl main() have params or return a value?

texts: I haven't ever seen anyone declare main as anything but void main() or void main(void) but I'm curious, is it possible to have a parameter or return value?


texts:
I'm using a 2D array of objects to store data about tiles, or "blocks" in my gameworld. I initialise the array, fill it with data and then attempt to invoke the draw method of each object.

foreach (Block block in blockList)
  {
    block.Draw(spriteBatch);
  }

I end up with an exception being thrown "Object reference is not set to an instance of an object".

What have I done wrong?

EDIT:
This is the code used to define the array

Block[,] blockList;

Then

blockList = new Block[screenRectangle.Width, screenRectangle.Height];
  // Fill with dummy data
  for (int x = 0; x <= screenRectangle.Width / texture.Width; x++)
  {
    for (int y = 0; y <= screenRectangle.Height / texture.Width; y++)
    {
      if (y >= screenRectangle.Height / (texture.Width*2))
      {
        blockList[x, y] = new Block(1, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture);
      }
      else
      {
        blockList[x, y] = new Block(0, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture);
      }
    }
  }


texts: Paint a 3D object partially and get percentage of a color in Unity 5 and C#

texts:
Im trying to paint an object partially from a raycasthit so it looks partially painted like in Splatoon or e.g.

Is there a way to get this working in 3d, without creating a new gameobject everytime?
And is there a possibility getting the pixels of a texture in 3d to calculate the painted percentage of the object?

I tried using 2D sprites and get the pixels from a raycasthit2d, but it didnt work out well. Has anyone an idea? Or has anyone an example for this?

I found some examples on grafittis and footsteps but they are either too old or dont fit...


texts: How can I emulate Diablo 3's Isometric view using Perspective?

texts:
Using DX11, SimpleMath I am building a isometric game like Diablo 3 in 3D and I want to use a perspective camera that emulates their top down view.

Projection Matrix: CreatePerspectiveFieldOfView(1, width/height, 0.1f, 100.0f);

But after this I am a bit unsure how I am suppose to rotate the camera. I assume I could just do p - Vector3(10, 10, 10) to get a 45 degree angle at any given p.

How do I properly position, and rotate the camera and point it at position p, to mimic Diablo 3 view?


texts: What are some low-level performance tweaks for iPhone games written in c?

texts:
I'm interested in some performance tweaks for a relatively simple OpenGL ES based 2D iPhone game.  What performance tweaks have you found?  The performance of the game is pretty good on most devices (3G, 2nd gen touch, and iPhone 4)... But I still want to give the user the best experience possible.

p.s. I'm still using OpenGL ES 1.1


texts: Should I keep login server apart from game server?

texts:
I'm thinking of making a MMO server, and I've been looking at how other games structure their network. One of the things I've noticed is that there's always a Login server and then the game server(s).

I'm still deciding if I should do this, but I would like to hear some opinions first.
What are the advantages of this, and how does the login server communicates with game server to handle logins?


texts:
I am designing an FPS game and scripted this shooting enemy that is supposed to shoot at the player if he is in the trigger zone once every second, but it just rapid fires and InvokeRepeating doesn't seem to do anything. No errors or anything. I am new to programming so it is most likely a rookie mistake. So here is the code

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

public class EnemyAI2 : MonoBehaviour
{
    public float fireRate = 10f;
    public float CanShoot;
    public float forceadded;
    public Transform BulletSpawn;
    public Transform PlayerTransform;
    GameObject player;
    NavMeshAgent enemy;
    public GameObject bulletclone;

    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        enemy = GetComponent<NavMeshAgent>();
        {
            InvokeRepeating("OnTriggerStay", 1.0f, 1.0f);
        }
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 direction = PlayerTransform.position - this.transform.position;
        enemy.destination = player.transform.position;

    }

    void OnTriggerStay(Collider other)
    {
        if(other.gameObject.tag == ("Player"))
        {
            gameObject.GetComponent<NavMeshAgent>().enabled = false;
            {
                Vector3 direction = PlayerTransform.position - this.transform.position;
                {
                    var Bullet = (GameObject)Instantiate(bulletclone, BulletSpawn.position, BulletSpawn.rotation);
                    Bullet.GetComponent<Rigidbody>().velocity = Bullet.transform.forward * forceadded;
                    Destroy(Bullet, 1.0f);

                }

            }
        }
        else
        {
            gameObject.GetComponent<NavMeshAgent>().enabled = true;
            enemy.destination = player.transform.position;
            Vector3 direction = PlayerTransform.position - this.transform.position;
        }
    }
}


texts: Limiting framerate with a fixed timestep

texts:
UPDATE:

I still need help determining how MAX_UPDATES works.  I want my game to be designed in such a way that if the user can't run the game at full speed, it slows down so that no updates are missed.. can someone help me understand that part of the code?  Also, how can I calculate an accurate realtime fps?

double frametime = 1000000./60, remainingTime = 0;
const unsigned int MAX_UPDATES = 10;

void Game::gameLoop(sf::RenderWindow &window)
{
    remainingTime += clock.restart().asMicroseconds();
    unsigned int updates = 0;
    while (remainingTime >= frametime)
    {
        remainingTime -= frametime;
        if (updates++ < MAX_UPDATES)
        {
            update();
        }
    }
    render(window);
}

Hi I'm learning how to create a 2d platformer in C++ using the SFML2 library.  My current goal is limiting the game's framerate.  SFML2 has a  window.setFramerateLimit(unsigned int limit) function for the window however I have found it to be imprecise due to it using sf::sleep.  Therefore I'm attempting to implement my own solution.  I want my game to used a fixed timestep and be framerate dependent as in the future when I implement attacks I want them to be based on frame data.

Since the game loop wont always execute exactly when a frame is supposed to happen, I create a delta variable that will account for the extra time spent starting the frame to start the next frame earlier by that same amount.

Does this all look right?

double frametime = 1000000./60, delta = 0;
void Game::gameLoop(sf::RenderWindow &window)
{
    t = clock.getElapsedTime().asMicroseconds();
    if (t + delta >= frametime)
    {
        clock.restart();
        delta = t + delta - frametime;
        update();
    }
    render(window);
}

edit: double shouldn't have f suffix doh


texts: Moving an object extremely close to the camera at a constant speed makes it visually speed up

texts:
I have a quad in 3D space (a billboard in the real-world sense) that I want to move close to the camera so the user can inspect it. The quad is defined by the 3D coordinates of its four corners.

To accomplish this I compute target points very close to the camera for each of the corners.

(I use XNA's Viewport.Unproject() method which does something similar to this)

// Top left corner of the screen,
// Z=0.1f means very close to the camera's near plane
var screenPoint = new Vector4(0,0,0.1f,1);
var worldPoint = Vector4.Transform(screenPoint, Matrix.Inverse(ViewMatrix * ProjectionMatrix));
var worldPoint /= worldPoint.W;

These world points that are close to the camera produce a very small quad: which is understandable if we look at this picture:

Here the initial position of the quad is depicted in red and the end position of the quad is depicted in blue.

For each of the corners of the quad I linearly interpolate between the original position and the position near the camera.

this.timer += deltaTime;
var progress = this.timer / 10.0f;
var currentTopLeft = Vector3.Lerp(initialTopLeft, nearTopLeft, progress);

Since I linearly interpolate the quad moves to its new position at a constant speed. I've verified this by ouputting the speed and distance to the console. However, the visual effect is that the quad first hardly moves and then all of a sudden moves very fast to its destination.

I think this is because the quad is being scaled down while moving closer (to fit the near plane) so it will stay relatively the same size on screen for a long time. Only once it comes very close it seems to move. (For example see this answer).

The question I have is: what can I do to make it look like the quad is moving closer at a constant speed?

I was thinking about not interpolating linearly but first move progress very fast and then very slow (Ive tried progress = sqrt(progress) which helped a little). But I'm not sure how I can compute the exact (or near enough) formulate to make this work.

Another idea I had was to bring the quad not so extremely close, but then there is the danger of it clipping with objects in the world.


texts:
After playing games like Star Wars Battlefront & GTA 5 I was wondering how dev's implement Color Correction in their Engines. I know that this can be done through the use of 3D LUT's but I was wondering if there are any other ways to do this. A good example of this would be in GTA 5 when a Characters special ability is triggered the colors on screen have a tint applied to them which over a period of 2 seconds the intensity of the effect gradually increases.

https://www.youtube.com/watch?v=LNGF7J3y5_Y

If someone can explain how this is done/ implemented that would be great.


texts: What is the name of the balancing technique that reduces the incremental value of bonuses?

texts:
Some games, including Dungeon Crawl (example), use a balancing technique that attempts to prevent certain values (stats, damage, etc.) from being excessively high. The algorithm looks like this:

if value > 20:
  value = 20 + (value - 20)/2
#70 → 45

...and can be applied multiple times:

if value > 20:
  value = 20 + (value - 20)/2
if value > 40:
  value = 40 + (value - 40)/2
# 70 → 45 → 37.5


texts:
I want to change TextField input type . When I click on the textfield the android keyboard appears with all the symbols , but I want only numbers and dot (.) .

TextFieldStyle textFieldStyle = new TextFieldStyle(font_38, Color.valueOf("646b6c"), getDrawable(atlas.findRegion("textField_cursor")), getDrawable(atlas.findRegion("textField_selection")), getDrawable(atlas.findRegion("textField_bg")));
TextField textField = new TextField("", textFieldStyle);
textField .setTextFieldFilter(new TextFieldFilter.DigitsOnlyFilter());

I have done in this way but here the only inputs are numbers and there is no dot . And when I click on the textfield again android keyboard appears with all the symbols , but I can type only numbers . There is a keyboard in android only with numbers , how to open it instead of all the symbols keyboard and type numbers and dot?


texts: I'm making a game using unity. In the game I've a purchasable product "remove ads". Where should I store user purchase data? If I use player prefs data will restore after a reset or uninstall.


texts: Bring GameObject in front of GUI Texture

texts: I have a GUI Texture that dims the screen, however I want certain game objects to not be dimmed. I tried putting them in front of the GUI Texture, but it doesn't work. How can I do this?


texts: How can I check if the player clicks (or doesn't) on a target within a time limit?

texts:
In GameMaker, I'm trying to set up something like this:

The player will need to click on some object within three seconds. If they click on it within the timeframe, I'll do one thing (call room_restart()). Otherwise the game is over.

How can I set this up?


texts: ECS Reference another Entity's Properties

texts:
In an entity component system (implemented where components only contain data and systems operate on groups of data) one can guarantee that the entity in which a system is operating on has the desired data. For example, a MovementSystem only operates on an entity if it has both Transform and RigidBody components. The MovementSystem knows as a matter of fact that the entity has all the data required to perform its logic. The problem I find is if a system needs to operate on another entity's properties - we cannot guarantee that this other Entity has the data we want to operate on.

Lets use a contrived example because I like code

DamageComponent:

DamageComponent(target, damage) : Component {
    Entity target = target;
    int damage = damage;
}

HealthComponent:

HealthComponent(health) : Component {
    int currentHealth = health;
}

The System:

DamageSystem() : System {
    // Operates on all Entities which have a DamageComponent

    DamageComponent dc = this.entity.getComponent(DamageComponent);

    // damage the target every update tick
    void update(dtime) {
        HealthComponent health = dc.target.getComponent(HealthComponent);
        health.currentHealth -= dc.damage;
    }
}

You see, a problem arises if the target Entity does not have a HealthComponent. What if the Entity never had a HealthComponent or some other game logic removed the HealthComponent? Is it typical to check every time if the target Entity has the desired Component?

if (dc.target.hasComponent(HealthComponent) {
    //...
}

I'm looking for a more "elegant" approach, if one exists. Thank you


texts: How do OpenGL's texelFetch and texture differ?

texts:
I understand the main differences between texelFetch and texture, but have some questions about the details:

Does texelFetch involve a performance penalty? Such as not using a cache or such?
Are texelFetch and texture interchangeable when using GL_NEAREST?


texts: Love2D STI library not drawing map at all (black screen)

texts:
I'm trying to use a pretty standard map with the Simple Tiled Implementation module for Love2D, but no matter what I try, I can't get it to display anything but a black screen. Here's my current code (keybindings in an effort to see if the map has just been placed offscreen):

local sti = require "sti"
local mapPos = { x = 0, y = 0 }

function love.load()
   map = sti("maps/map1.lua")
end

function love.update(dt)
   if love.keyboard.isDown("w") or love.keyboard.isDown("up") then
      mapPos.y = mapPos.y - 5
   end

   -- Move player down
   if love.keyboard.isDown("s") or love.keyboard.isDown("down") then
      mapPos.y = mapPos.y + 5
   end

   -- Move player left
   if love.keyboard.isDown("a") or love.keyboard.isDown("left") then
      mapPos.x = mapPos.x - 5
   end

   -- Move player right
   if love.keyboard.isDown("d") or love.keyboard.isDown("right") then
      mapPos.x = mapPos.x + 5
   end
   map:update(dt)
end

function love.draw()
   -- Transform world
   love.graphics.translate(-mapPos.x, -mapPos.y)

   -- Draw world
   map:draw()
end

However, even a more basic attempt (copied from the STI tutorial linked from the README on the Github page) doesn't work, again giving a black screen:

-- Include Simple Tiled Implementation into project
local sti = require "sti"

function love.load()
    -- Load map file
    map = sti("map.lua")
end

function love.update(dt)
    -- Update world
    map:update(dt)
end

function love.draw()
    -- Draw world
    map:draw()
end

My directory structure is basically just main.lua, an assets folder, and a maps folder. The maps folder contains the Tiled tile set and the Tiled .tmx maps and the lua exported maps.

I'm on Mac OSX, using Love2D version 0.10.2.

Am I missing something? Thanks.


texts: How to calculate Joystick margins/thresholds?

texts:
On a joystick that gives float position values from -1 to 1 on either of x and y axis, how do I implement the math that adds "lower" and "higher" circular margins?

For example if lower margin is 25% (0.25 float) of radius, and higher margin is 50% (0.5 float), it might look like this:

The actual "hot" zone is green,  meaning:

Grey area should always give 0,0 readings of x/y.
Green area should give actual values of x and y form range -1 to 1.
Blue should always give 1 or -1.


texts: Adding an object viewer to a Unity Editor Window

texts:
I'm wondering if its possible to add an object viewer (For example when you import an .fbx file into unity you can see a small preview of it in the inspector) to a Unity Editor Window? I've looked through the docs and didn't seem to be able to find anything for this

Thanks,

Lewis


texts: What's the name of the "Candy Crush" style of game?

texts:
I'm currently creating an engine trying to auto-play games with a chess board, and I'm writing a report about it now.

However, I found it hard to properly describe it -- for the games like Candy Crush, which has a game board, filled with "candies," and a few rules.. is there a formal classification for it?

Is "board-game" a proper name? What about "rectangle-tile game", or "chessboard-based game?"


texts: Wall jumping collision detection anomaly

texts:
I'm creating a game where the player ascends a tower by wall jumping his way to the top. When the player has collided with the right wall they can only jump left and vice versa. Here is my current implementation:

    if(wallCollision() == "left"){
        player.setPosX(0);
        player.setVelX(0);
        ignoreCollisions = true;
        player.setCanJump(true);
        player.setFacingLeft(false);
    } else if (wallCollision() == "right"){
        player.setPosX(screenWidth-playerWidth*2);
        player.setVelX(0);
        ignoreCollisions = true;
        player.setCanJump(true);
        player.setFacingLeft(true);
    } else{
        player.setVelY(player.getVelY() + gravity);
    }

and

private String wallCollision(){
    if(player.getPosX() < playerWidth && !ignoreCollisions)
        return "left";
    else if(player.getPosX() > screenWidth - playerWidth*2 && !ignoreCollisions)
        return "right";
    else{
        timeToJump += Gdx.graphics.getDeltaTime();
        if(timeToJump > 0.50f){
            timeToJump = 0;
            ignoreCollisions = false;
        }
        return "jumping";
    }
}

If the player is colliding with the left wall it will switch between the states left and jumping repeatedly due to the varible ignoreCollisions being switched repeatedly in collision checks. This will give a chance to either jump as intended or simply ascend vertically instead of diagonally.

I can't figure out an implementation that will reliably make sure the player jumps as intended. Does anyone have any pointers?


texts:
As most of intermediate graphics programmers know, z-fighting can be a problem. That's why most game engines prevent this from happening by using a slope depth bias algorithm.

As there's no direct information on how this is performed, apart from microsoft's reference DirectX page, I wanted to ask whether anyone has any idea on how a vertex shader could be written to implement such a mechanism. I wrote a snippet, but it's not behaving as expected. Here it is (Cg vertex shader code):

out_position =  mul(worldviewproj_matrix, in_position);
out_world_position = mul(world_matrix, in_position);

float Dz = camera_position.z - out_world_position.z;
float Dy = camera_position.y - out_world_position.y;
float Dx = camera_position.x - out_world_position.x;
float m = max( abs(Dz / Dy), abs(Dz / Dx));
float Offset = m * main_bias + main2_bias;
out_position.z -= Offset * 0.005;


texts:
Hello everyone i have a question about animating multiple enemies on the screen at the same time.

Basically, i figured out how to use the Pool for creating enemies and dispose them after use etc..
All enemies are equal to each other, and all enemies have 3 different animations for creating, moving, destroying.

Everything is working fine, but when i have multiple enemies on screen, they are all animating at the same times, even if they were (obviously) created in different times.

For example, i create 3 enemies, make them moving on the screen and they all have the same frame.. the animation must be the same for all, but i expected that the time when they change frame should be different.

The animations are instantiated inside the Enemy class, so i guess every instance of Enemy must have its own animation.

This is how i draw them in the Renderer class:

private void drawEnemies(float runTime) {
    enemyArrayLen = catta.activeEnemies.size;
    for (int i = enemyArrayLen; --i >= 0;) {
        currentEnemyAnimation = catta.activeEnemies.get(i).getCurrentAnimation();
        batcher.draw(
            currentEnemyAnimation.getKeyFrame(runTime),
            catta.activeEnemies.get(i).getX(),
            catta.activeEnemies.get(i).getY(),
            catta.activeEnemies.get(i).getWidth() / 2.0f,
            catta.activeEnemies.get(i).getHeight() / 2.0f,
            catta.activeEnemies.get(i).getWidth(),
            catta.activeEnemies.get(i).getHeight(),
            1,
            1,
            0
        );
    }
}

Enemies are stored in the catta.activeEnemies array.

currentEnemyAnimation is a "support" variable in which i put the Enemy in every cicle of the for cicle.

This is how i initialize an Enemy:

public void init(float posX, float posY, int width, int height) {
    this.position.set(posX,  posY);
    this.width = width;
    this.height = height;
    this.alive = true;
    this.enemyRunTime = 0;
    this.creationTime = 0.8f;
    this.destructionTime = 0.8f;
    this.crea_Animation = AssetLoader.enemy_creaAnimation;
    this.crea_Animation.setFrameDuration(this.creationTime / 4);
    this.mo_Animation = AssetLoader.enemy_moAnimation;
    this.des_Animation = AssetLoader.enemy_desAnimation;
    this.des_Animation.setFrameDuration(this.destructionTime / 4);
    this.enemyState = EnemyState.CREATING;
    ...

Maybe it's all a runTime and delta matter?


texts: Set FBX creator while exporting using FBX SDK

texts:
I am using FBX SDK 2018.1.1 to write a simple utility application on windows that will export existing FBX file (this file is exported from Blender 2.79).

I need to set the creator of the final FBX file to "My custom FBX exporter". As per documentation of FBX SDK, it can be done using

http://help.autodesk.com/cloudhelp/2018/ENU/FBX-Developer-Help/cpp_ref/class_fbx_i_o_file_header_info.html

here is the code snippet used to export the FBX:

FbxExporter* pExporter = FbxExporter::Create(m_pSdkManager, "");

pExporter->SetFileExportVersion(FBX_2012_00_COMPATIBLE);

FbxIOFileHeaderInfo *infoExporter = pExporter->GetFileHeaderInfo();
infoExporter->mCreator = "My custom FBX exporter";

pExporter->Export(m_pScene);
pExporter->Destroy();

But when I read this newly exported FBX file it shows "FBX SDK/FBX Plugins version 2018.1.1" in the mCreator field.
This is the snippet when I import the file (just to check if mCreator property is properly set)

lImportStatus = lImporter->Import(m_pScene);

info = lImporter->GetFileHeaderInfo();

How do I properly set the mCreator in FBX file header so that it is set in final exported file?


texts: AS3: Using singletons for sound managers

texts:
Is it necessarily a bad thing to use a singleton for a sound manager?

I am having a really tough time determining whether or not I should go ahead and use a singleton (which is easy/it works) or if I am shooting myself in the foot by deviating away from good OOP principles (since a singleton is basically a glorified single-instance global variable of sorts).


texts: JAVA -- Should I use a float or double for 1.5 speed for my player's speed? What should I use in general for positions, etc.?

texts: The title says it all, but I would like to know if I should use a double 1.5 for my velX and velY factor, or a float 1.5 for my velX and velY factor. Also, I would like to know if I should use a double or float for everything such as positions of entities, etc.. Thanks in advance!


texts: Does "Personal Use" mean I can earn from it?

texts:
I'm almost done with my personal game. One of the reasons I started this is because of monetization. I plan to monetize it using Google Admob. However, I need some icons - essential part of my game.

And these icons are free, released by a certain company, and they say in their download page:

  These icons are free for personal use or commercial testing purposes.
  Otherwise, you'll need a Premium or Enterprise license. :)

Question is, does "Personal Use" mean I can earn from it?

Also, this "personal game" is actually "under" a group named, say "XXX".
The group "XXX" is merely a group name, not a company, not legal/registered, just literally a group name on Github. And this group is composed of 3 people and that includes me. Does this kind of setup go under the "personal use"?


texts: How do I align textures properly with an exploding sprite / breakable body?

texts:
I'm working on a game based on Box2D and Starling which includes breakable bodies - bodies/objects that when hit with sufficient force break apart (into smaller pieces).
I've managed the physics part but I'm stuck on the graphics.

Using the old non-Stage3D  Flash APIs I would do something like this to draw the resulting pieces of the breakable body (after the impact):

       var m:Matrix = new Matrix();
        m.tx=- texture.width*0.5;
        m.ty=- texture.height*0.5;

        this.graphics.lineStyle(1);
        this.graphics.beginBitmapFill(texture, m, true, true);
        this.graphics.moveTo(verticesVec[0].x, verticesVec[0].y);
        for (var i:int=1; i<verticesVec.length; i++) {
            this.graphics.lineTo(verticesVec[i].x, verticesVec[i].y);
        }
        this.graphics.lineTo(verticesVec[0].x, verticesVec[0].y);
        this.graphics.endFill();

The verticesVec contains the vertices of the piece I want to draw.
In Starling I've managed to draw the pieces using a fragment shader like so:

      fill = new Fill();
      fill.material.fragmentShader = new TextureVertexColorFragmentShader();
      //fill.material.textures[0] = Assets.getTexture("Box");
      fill.addVertex(verticesVec[0].x,  verticesVec[0].y,0x000000);

      for (var i:int=1; i<verticesVec.length; i++) {
               fill.addVertex(verticesVec[i].x,  verticesVec[i].y,0x000000 );
      }

     fill.addVertex(verticesVec[0].x, verticesVec[0].y,0x000000 );

But I can't figure out how to manipulate the texture so it fits my pieces.
When I try adding a texture it ends up stretched/rotated, etc.

I'm kind of new to shaders and I would really appreciate a push in the right direction.


texts: How would you structure a weapon class such that it works for many types of weapons?

texts:
How would you go around creating a reusable weapon class? I can't really wrap my head around creating a class, which will work for both melee and ranged weapons.

Example given, that you have a knife, an RPG, and you have an ordinary pistol. How would you go around creating a class all three can inherit from?


texts: Enabling Unity GUI drawtexture permanently?

texts:
I'm trying to get an image to show in Unity based on a certain criteria.
I would like the position of the image to be randomized every time on play.

However since GUI.DrawTexture shows the image for a single frame only, I end up with the image flashing across the screen in random areas. I would the first location to be randomized and the image to remain still there.

Any advice on how to perform this will be greatly appreciated.

Code:

void OnGUI(){
 if(HP>=0.9f){
   GUI.DrawTexture(new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300) aTexture);
  }
}


texts: Trouble with assigning a model's own mesh to a mesh collider in Unity

texts:
I'm trying to use a mesh collider on the player's avatar, rather than the box collider.

I've added the mesh collider to the game object (which also has a rigid body) and selected the "convex" checkbox.  However, the player still falls through all geometry, including Unity primitives, terrain, and other models.

In the mesh collider's property box, there's a value for "Mesh", which I have set to "None (Mesh)".  I was led to believe this defaults to the model's own mesh, but now I'm not certain.  If I change the value to something else from the "select mesh" list, like the cube, the collisions work.  When I click over to Select Mesh --> Scene, the list is empty.  I'm assuming I need to add the model's mesh to the list, but I can't find any documentation about that.


texts: How do I move from mainstream to indie development?

texts:
I'm a game programmer for a AAA-level developer and publisher—which I know falls into the 'nice problem to have' category. However, I'm becoming disenchanted with the direction of both the company and the AAA-portion of the industry as a whole.

I want to do something fundamentally different.

It seems the market has never been better for smaller-scale projects, and I'd love to jump into that (and I've done small demos for Android and have started digging into iOS), but I obviously can't put anything out while I'm working for the company. I'm concerned that I shouldn't even do substantial development in my spare time on anything I'd eventually like to release on my own.

At the same time, I'm leery of leaving my job, for hopefully-obvious reasons, especially without a specific plan in place.

Has anyone out there got experience with 'going indie' out of a mainstream job? Do you have specific suggestions as to a best approach and what to specifically think about or be careful of?


texts: How to automatically delete an object in Unity?

texts:
I am new to unity and the other day I was wondering that it would be useful if I could instantiate some objects in my game scene and, as they get instantiated, make it so that they get automatically deleted after a period of time.

I thought about automatically adding a Destroy script to them so that they could be deleted after a period of time using:

Destroy(Gameobject, time);

I'm not sure that's what I need, and if it is I don't know how I'd go about it.

How could I make it so that my objects get automatically deleted after some time, in the context that I'll have a lot of them?


texts: How could I make the player's movement more responsive?

texts:
I am working on an Air Hockey game;
I tried making the movement physics-based, by doing this:
using UnityEngine;

public class Player : MonoBehaviour
{
    private Rigidbody m_Rigidbody;

    private float HorizontalInput;
    private float VerticalInput;

    public float Speed = 1.0f;

    private void Start()
    {
        m_Rigidbody = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        HorizontalInput = Input.GetAxisRaw("Horizontal");
        VerticalInput = Input.GetAxisRaw("Vertical");
    }

    private void FixedUpdate()
    {
        m_Rigidbody.AddForce(new Vector3(VerticalInput * Speed, 0.0f, -HorizontalInput * Speed),ForceMode.VelocityChange);
    }
}

and by adding a PhysicsMaterial to the MeshCollider attached to my player:

The movement should be quick and responsive, but it feels rather sloppy and unresponsive; I also tried using Input.GetAxisRaw(...), but the controls become quite clunky.
How can I improve on this? Is there a go-to way to do this type of movement in Unity?
(I would like the final version of the game to be played on controllers)


texts: shooting bullets without players being able to cheat

texts:
I'm working on a multiplayer game and for bullets that players shoot I was wondering what is the right way to do it:

when a player press a key It send the key code to server and:
a. server starts moving the bullet and sends the bullet location to clients
b. server tells the clients to generate a bullet and move it in angle x, with speed of x for duration of x

well the second way makes more sense but I'm worried about players being able to cheat in the second way. So How should I do this without players being able to cheat?


texts: Project collision shapes to plane for 2.5D collision detection

texts:
I am working on a top down 2.5D game. In the game anything that overlaps on the screen should be 'colliding' with each other regardless of whether they are on the same plane in the 3D world. This is illustrated below from a side-ways view:

The orange and green circles are spheres floating in the 3D world. They are projected onto a plane parallel to the viewport plane (y = 0 in the image) and if they overlap there is a collision event between them. These spheres are attached to other meshes to represent the sphere bounding boxes for collisions.

The way I plan to implement this at the moment is the following:

Get the 3D world position at the center of the sphere.
Use Camera.WorldToViewportPoint to project the point to the viewport plane.
Move a Sphere Collider with the radius of the sphere to that point.
Test for collisions using unity colliders.

My question is how to extend this to work for rotated cuboids. For instance if I have two rotated cuboids, if I follow the logic above it would not work as intended as the cuboids may not collide but they could still be intersected on the view plane. An example is below:

In the example above the cuboids are overlapping from the view of the player, but not colliding when they should be.

Is there a way to project a cuboid that would be aligned with the plane? Would it be a valid cuboid for all rotations if I did this?

EDIT: Corrected the images, before they were incorrectly projecting onto the y=0 plane at 0 rotation, not the plane parallel to the viewport plane.


texts: What time to display in text messages in multiplayer game?

texts:
Say I'm having a multiplayer RTS game. There's a main server for each individual game and several clients connected to it. All packets are sent to server first and then server retransmits them back to clients.

Say Server is located in one time-zone and all of the clients are in different time-zones.
ClientA send a text message in chat at 12:03, what times should be stamped for other clients? Should his message be uniformely timestamped by Server (12:02) or each client should timestamp the message whenever it is recieved (12:04, 16:04, 03:03, etc..). Bear in mind, that all the messages are to be in the same order on all clients, server takes care of that.

So thats the question - use local time for each client or use global server time to timestamp chat messages?


texts: How is this glowing with colors radiating outward 2D effect accomplished?

texts:
I'm currently totally at a loss as to how this effect is done:
http://www.youtube.com/watch?v=zp8MHUNp7Cg

The glowing on the ship and the changing color. I want to do this effect in XNA 4.0 any hints and tips?


texts:
I wanted to load in map information using JSON, is there a way to get String, Int, float etc lists or arrays from JSON in Libgdx?

My structure looks like this

{
    "data": [{
        "name": "startmap",
        "actors": [{
            "name": "ryder"
        }]
    }]
}

And I want to get Actors as either a String List or Array, but there is no GetList or GetArray function. Is there any other way to do this?


texts:
In the context of lag compensation, one needs to know when the command is instantiated on the client (this can be named as "command execution time" as well). AFAIK, there can be 2 methods for this:

Client sends a timestamp with the command.
Client doesn't send any timestamps, but server does a smart thing to calculate the command's instantiation time.

About #1:

Is this safe in terms of cheating?

About #2:

According to Valve's paper, command execution time is as following:

  Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation

This means, server must know the packet latency.

Another paper from Valve confirms this and says:

  Before executing a player's current user command, the server:

  Computes a fairly accurate latency for the player
  ...

How can the server compute "fairly accurate latency for the player"?

Most naive and easiest approach would be sending pings regularly (less frequent than game commands and updates though) to find out an average of the latency and use it. Busy network traffic, latency fluctuation and naiveness of this method makes me feel there must be a more elegant way.

EDIT: Would UDP vs TCP change anything in this context?


texts:
I have been looking around for implementation details of behavior trees, the best descriptions I found were by Alex Champarand and some of Damian Isla's talk about AI in Halo 2 (the video of which is locked up in the GDC vault sadly).

However, both descriptions fall short of helping one actually create a BT, one particular question has been bugging me for a while.

When is the tree in a behavior tree evaluated?

Furthermore:

If the tree is in the middle of executing a sequence of actions (patrolling waypoints) and a higher priority impulse comes in (distraction sound) , how to switch to that side of the tree seamlessly without resorting to a state machine like system and if it is decided that the impulse was irrelevant (the distraction is too far away to affect this guard), how to go back to the last thing that the guard was doing ?

I have quite a few questions like this and I don't wish to flood the board with separate queries so if you know of any resource where questions like these can be answered I would be very grateful.


texts: How can I customize scrollbar sensitivity in editor property drawers in Unity3D?

texts:
A custom property drawer, in my Unity 2017.3 project, has code like this in its OnGUI implementation:

public void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
    ...
    EditorGUI.BeginDisabledGroup(maxX == 0);
    scrollX = (uint)GUI.HorizontalScrollbar(new Rect(xyPos + new Vector2(slHeight, normalizedSize), new Vector2(normalizedSize, slHeight)), scrollX, 1, 0, maxX + 1, GUI.skin.horizontalScrollbar);
    EditorGUI.EndDisabledGroup();
    EditorGUI.BeginDisabledGroup(maxY == 0);
    scrollY = (uint)GUI.VerticalScrollbar(new Rect(xyPos, new Vector2(slHeight, normalizedSize)), scrollY, 1, maxY + 1, 0, GUI.skin.verticalScrollbar);
    EditorGUI.EndDisabledGroup();
    ...
}

But these scrollbars have a sensitivity of 10 (pressing the up/down, or left/right, buttons will change the current value by 10 in the respective direction). I need them to have a sensitivity of 1. How can I do it?


texts: Architecture for extremely modular game?

texts:
I'm developing a modular game in Unity 5.6. Each module has very little overlap in assets with the others. I'm concerned about having a bloated repository after a few months of development, and since I'm using Bitbucket (a free account) I'm limited in my repo size, but not in my number of repos. So instead of having one huge folder for my game I'm considering having a launcher project and scene that loads builds from a folder in /Assets. Each module would be its own project, and I would just drop its build into the launcher's folder.

My question is, is this a reasonable approach to building a highly modular game? Hopefully I'll be continuing development for quite a while, and I want to make sure the project is as lightweight and extendable as possible. Or am I overthinking this, and should I just use one big repo?


texts: Synchronizing players and game objects in a server/client multiplyer game

texts:
OK guys,
I have some experience with 2D game development (single player only), so that's fine no questions here.

The problem is with multiplayer games. I already read lots of other questions and articles to get my head around about peer-to-peer and server/client, and non-authoritative and authoritative game clients.

What am I trying to achieve?
Build a simple 2D multiplayer game with some physics involved and over 40 player per game, a good example is flapmmo. However my game concept will be completely different and the players and other game objects will actually interact/collide with each other.

What technologies have I chosen?
Client: Unity3d (easy to develop and cross-platform)
Server: Node.js + socket.io + express.js (easy to deploy and cheap to host)

What I have done so far:
I already have a test client and server running and the players connection/join game + spawning works just fine. Now I am stuck at how to synchronize all the objects + players.

Base on that:

1 - How do I simulate physics on the server, do I need to rewrite parts of client side on the server side using a JavaScript physics engine?

2 - Is it better to send action messages like "playerJumped" and broadcast it to the clients or send it's current position on every update (more bandwidth consumption I guess)?

3- I read the server needs to run on a lower frequency( E.g. 30hz) to better perform with latency issues. Is it FIXED_TIME_STEP that we are talking about?

Please feel free to add any other important point I should consider...
Tks


texts: Rotating object along bezier curve: not rotating enough?

texts:
I tried to follow the instructions from the threads on the forum (Cocos2d rotating sprite while moving with CCBezierBy) with Unity, in order to rotate my object as it moves along a bezier curve. But it does not rotate enough, the angle is too low, it goes up to 6 instead of 90 for example, as you can see on this image (the y eulerAngle is at 6, I would expect it to be around 90 with this curve) :

EDIT: here is the solution :

Vector3 v3 = newPos - oldPos;
v3.y = 0.0f;
transform.rotation = Quaternion.LookRotation(v3);

Here is the code (in c# with Unity) : (I am comparing x and z to get the angle, and adding the angle to eulerAngles.y so that it rotates around the y axis)

void Update () {
        if ( Input.GetKey("d") ) start = true;
        if ( start ){
            myTime = Time.time;
            start = false;
        }
        float theTime = (Time.time - myTime) *0.5f;
        if ( theTime < 1 ) {
            car.position = Spline.Interp( myArray, theTime );//creates the bezier curve
            counterBezier += Time.deltaTime;

            //compare 2 positions after 0.1f
            if ( counterBezier > 0.1f ){
                counterBezier = 0;
                cbDone = false;
                newpos = car.position;
                float angle = Mathf.Atan2(newpos.z - oldpos.z, newpos.x - oldpos.x);
                angle += car.eulerAngles.y;
                car.eulerAngles = new Vector3(0,angle,0);
            }
            else if ( counterBezier > 0 && !cbDone ){
                oldpos = car.position;
                cbDone = true;
            }

Thanks


texts: OnTriggerEnter error: The message parameter has to be of type: Collider

texts:
I have a crate and I want to make it so if you are in the trigger of the crate a UI appears and says "Click E to loot".
I have the UI setup but the script is not working. Here is my script and after it are the errors.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_Appear : MonoBehaviour
{
    [SerializeField] private Image image;

    void OnTriggerEnter(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            image.enabled = true;
        }
    }

    void OnTriggerExit(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            image.enabled = false;
        }
    }
}

The errors say:

Script Error: OnTriggerEnter
The message parameter has to be of type: Collider
Script Error: OnTriggerExit
The message parameter has to be of type: Collider


texts: What's the generally accepted way to coordinate game events between objects?

texts:
I'm a newbie when it comes to game development and I'm struggling to decide on a good and consistent architecture for having child game objects trigger actions at a higher parent level.

For instance, say that I have game objects like this (in Unity)

This is a conceptual heirarchy, not the actual Unity scene heirarchy.  GameManager and PlayerStats are ScriptableObjects in Unity.  I have the hierarchy drawn like this because each scene can be thought of as a child of the overall game.

GameManager (ScriptableObject)
|
|--> PlayerStats (ScriptableObject)
|
|--> Scene (the Unity scene)
     |
     |--> GUI (MonoBehaviour)
     |    |
     |    |--> Button (MonoBehaviour)
     |
     |--> Player (MonoBehaviour)
     |
     |--> Enemy1 (MonoBehaviour)
     |
     |--> Enemy2 (MonoBehaviour)

If I click the button in the GUI, I want the player to fire a gun.  That requires the following things to happen:

Check that the player's ammo is greater than zero (done in PlayerStats)
Instantiate a new bullet in the scene (done in Scene)
Update the player's ammo (done in PlayerStats)
Update the GUI to show the new ammo count (done in GUI)
Play the "fire" animation (done in Player)

The "fire gun" event is triggered from the Button object, but it needs to perform actions on objects that it is not an ancestor of.  There also needs to be some high-level coordination between objects, so that if the player is out of ammo, none of the subsequent actions take place.

Here are the ways I can think of to handle this logic, along with pros and cons:

1. Do all logic within the button's Fire() method

Pros

Simple (all code is directly in the button's click handler)

Cons

Violates single responsibility principle.  The button is now responsible for game logic.
The button has to have references to a bunch of higher level game objects.  This smells of poor design.

2. Have the button's click handler call GameManager.FireGun()

Pros

The entire event sequence is coordinated from a high-level game object that only acts on its children
The GameManager.FireGun() method can be called from any other game event that I want to fire the gun from

Cons

The GameManager class will be huge because it'll have a lot of these types of events.
The button has to call a method (FireGun()) from a higher-level object, and so it still has to have a reference to a parent object.  This seems like poor design.

3. The button's click handler puts a "fireGun" message on the bus, which is picked up by GameManager.OnGunFired()

Pros

Same pros as method 2, with the added benefit of the button not having a reference to its parent GameManager

Cons

Same cons as above.  GameManager will have a lot of "OnSomething" methods.
GameManager will have to subscribe/unsubscribe to a lot of messages.
Unit testing becomes more difficult.  Rather than checking to see if a method was called on a mock, each unit test will need to set up a message bus, and verify that the correct messages were sent.

4. Have GameManager, Player Stats, GUI, and Player all subscribe to the fireGun event

Pros

Code is split up between different classes, so GameManager won't end up with a bunch of big methods that coordinate every action.
Better adherence to single responsibility principle.  All inter-object communication is done with the message bus, so objects don't have to know about each other.

Cons

Difficult to do inter-object coordination, such as if the "fire" button is clicked and the player is out of ammo, none of the "fire gun" actions should happen.  That could be solved by doing an ammo check in the button's onClick, but again that would require the button to know about higher level player objects.
Same unit testing difficulties as method 3.

Among these four architectures, which one(s) tends to be the most common in games (or is there a better way of doing this that I didn't mention)?


texts: Interpreting focal length in units of pixels

texts:
I am working on a renderer of sorts and I have some fundamental questions. Let's say I have a vector in a 3D virtual world space which is unitless, and I want to project it onto a 2D screen, so I need its pixel position.

My background is in computer vision, so this is how I would model the problem.

p = K * [R | t] * v

where v is my 3D vector in homogenous coordinates. R is a 3x3 rotation matrix, t is a 3x1 translation vector, and K is a 3x3 "camera matrix". The camera matrix takes the following form

f 0 cx
0 f cy
0 0 1

f is the "focal length" of the virtual camera and cx, cy is the "principal point" in pixels (usually the center of the screen).

So, assuming my camera is at the origin (and static), [R | t] moves the 3D vector v somewhere in front of the camera and I get some v'. Now, I want to project 3D vector v' onto the screen.

v' = [x' y' z']^T

Kv' = [fx*x'+cx fy*y'+cy z']^T

Now, dividing by the perspective z' I get p.

p = [(fx*x'+cx)/z' (fy*y'+cy)/z' 1]^T

This certainly works in code and I'm getting favorable results in my renders.

But I fundamentally don't understand what it means to express focal length in terms of pixels. In a real camera it's the physical distance between the imaging plane and the focal point of the lens, but there's no such analog in 3D graphics.

Furthermore, I don't really see why the dimensional analysis works out, and why p is indeed in units of pixels.

Thanks for reading!


texts: How to get the closest "visible" object from my "player"?

texts:
I'm using Unity 3d and i have to accomplish the following task: get the closest "visible" object to my player in forward direction.

It is a sort of radar.

I don't know where to start.
Any advice is welcomed.

Thanks


texts: Indicating low vs high card wins in trick taking card game

texts:
I have a trick taking card game in which case there are occasions when the high card wins and occasions when the low card wins. Usually this is based on who lead the trick but some cards can change this mid hand.

I had an arrow icon to indicate this with it pointing up while a high card will win and low while a low card would win and a sound when this was changed mid-round.

This does not appear to be consistently conveying the desired message. What would be a better non-textual way to do so? I don't want to just put a bunch of text on screen because people would skip it and then get confused anyway or get annoyed by being made to read a bunch of text before playing.


texts: How can I handle inventory in an object-oriented way?

texts:
I'm trying to think of the best way to handle player inventory following an object oriented approach.

For example, sword and axe are two different classes, both inheriting from weapon. Weapon and potion are also different classes both inheriting from item.

Ideally, the inventory would be implemented as a container of items, but that can't be done for several reasons. So it has to be a container of item (smart) pointers. Since I don't want to liter my code with calls to new and delete, I'll wrap it in an ItemWrapper class which news/deletes on ctor/dtor.

So the code will look something like this

class Sword;
class ItemWrapper;

//Prepare the long sword.
const Sword longSword(...params...);

//Declare the inv
vector<ItemWrapper> inv;

 //Add it to inventory
inv.push_back(longSword);  //compiles if ItemWraper(const Sword&) is defined.

This approach was the best I could come up with in terms of code clarity and ease of writing. The problem is that ItemWrapper will need one constructor for each leaf class that inherits from Item (which is a lot).

This is my first attempt at this, so I'd like to know: am I going the right way? or if there's a better way of doing it (perhaps one that avoids so many constructors)?


texts:
I'm trying to write a little program with a bouncing cube but I can't find the right values for it.
I have these lines:
modelMatrix = glm::mat4(1)

modelMatrix *= Translate(x, y, z)

modelMatrix *= RotateOZ(angle)

RenderMesh(mesh["cube"], shaders["V"], modelMatrix)

I add/sub the y in a interval and the angle too.I have a problem because I don't really know with which values to increment/sub these values.

I want the same effect as in the image but at all angles [0 - 180].
EDIT++
So I want my cube to bounce while it's rotating like in the image. First the cube will have the arrow down to show what's his position first at y0 and x0. Then he will rotate in the [0 - 90] range. I want the cube to have the arrow up meaning that the cube will be rotated at 90 angle when he will hit y1 and x1/2. Then he will start to descend at an angle [90 - 180] so he will be at y0 but with at x1.
I tried incrementing the x, y and the angle with a small value like 0.1 and then decreasing the y when it hit a point. The result is close but I can see that it's not perfect.
I hope that made sense.
Thank you for your time!


texts: What should I do to get my Blender models into my iOS game?

texts:
I am working on a 3D OpenGL|ES game for iPad. All the models are created in Blender. How should I go about getting my models into my game?

I have the following requirements of my models:

One texture map
Material
Skeletal animation data
Attachables / Socket Points


texts: Error saying attempting to reference a deleted function while using a vector list

texts:
I’m making a 2d top down shooter game and I was working on shooting bullets. Im using a vector for the bullet in my player class:
std::vector b;
And I have coded a shoot function which shoots the bullet and deletes it if it is out of the screen:

void Player::shoot(float timer)
{
//Getting Key Press
if (Keyboard::isKeyPressed(Keyboard::Space))
{
    space = true;
}
else
{
    space = false;
}

Bullet b1;
b.push_back(Bullet(b1));

if (space)
{
    for (int i = 0; i < b.size(); i++)
    {
        b[i].setPos(pos);
    }

}
else
{
    for (int i = 0; i < b.size(); i++)
    {
        b[i].update(true);
        if (b[i].getPos().y < 0.0f)
        {
            b.erase(b.begin() + i);
            i--;
        }
    }
}
}

But I have encountered an error:
    Error   C2280   'Bullet &Bullet::operator =(const Bullet &)': attempting to
    reference a deleted function

I don’t understand why this is happening can someone explain?
Here is the bullet class
Header:

#pragma once
#include <SFML/Graphics.hpp>

using namespace sf;

class Bullet
{
private:
Texture t;
Sprite bullet;
Vector2f pos;
public:
Bullet();
~Bullet();
void setPos(Vector2f pos);
void move(bool up);
Sprite getSprite();
Vector2f getPos();
};

Cpp file:
    #include "stdafx.h"
    #include "Bullet.h"

Bullet::Bullet()
{
//Setting Texture
t.loadFromFile("Graphics/bullet.png");
bullet.setTexture(t);

}

Bullet::~Bullet()
{
}

void Bullet::setPos(Vector2f pos)
{

//Setting Position
this->pos = pos;
bullet.setPosition(this->pos);
}

void Bullet::move(bool up)
{
if (up)
{
    bullet.move(0.0f, -10.0f);
}
else
{
    //TODO
}
}

Sprite Bullet::getSprite()
{
return bullet;
}

Vector2f Bullet::getPos()
{
return pos;
}


texts: Implement 2x speed in tower of defense type game

texts:
I was currently developing tower of defense game and I want to implement 2x feature for my game. Game usually run with 1x speed that was normal speed of the game.

Here what 1x and 2x mean :
1x - mention normal speed of the game,
2x -  mention the game object moves with double speed means user experience the fast game play.

I want to implement such functionality for my game. The functionality that I want contains in the game Medieval Castle game that was available in the market.

https://play.google.com/store/apps/details?id=com.nova.root&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5ub3ZhLnJvb3QiXQ..

The screen shot also shows the 1x and 2x button in that game. I think for 2x speed of the game I have to increase the speed of each object that were in the game.

So any member please help what to do for that implementation. Only idea become enough for me.


texts:
I know this is kind of a basic question, but I'm trying to create my own game from scratch and really don't understand this. How does the code of a videogame program certain pixels to be certain colors and then move them in agreement with the player's movement?

For example, in a 2D platformer, how does the code program the on-screen visuals of the world that the player is in? And then, how does it move a certain object matching the speed of the player and then eventually have it go off screen?

Thanks in advance!!


texts: Making a Rigidbody return to being level

texts:
I am working on a game where mouse input affects the torque of the RigidBody but I would like the Rigidbody to return to being level if certain conditions are met.

Currently the angling working right but once you set the mouse in the deadzone and make the mouse_input equal to 0, then the RigidBody will teeter back and forth and not settle.

I would expect this act like so:

User angles the RigidBody to an angle to 45
User decides they are done and move the mouse to the deadzone, making the mouse_input 0.
The level function applies a mouse_input value of the opposite angle causing the RigidBody to level out.

I created a gift of the script below in action: https://giphy.com/gifs/TIcqjZnkiUR1azg3u6

extends RigidBody

# A deadzone where mouse motion has no effect.
var window_half: Vector2 = OS.get_window_size() / 2
var deadzone: Rect2 = Rect2(Vector2(window_half.x - 200, window_half.y - 200), Vector2(400, 400))

# The input amount set by mouse motion.
var mouse_input: float = 0.0
# The angle of the box.
var box_angle: float = 0.0

# Nothing to do in ready, pass.
func _ready():
    pass

# Each frame we check the mouse position and apply the correct force to make the body
# go in the desired direction.
func _process(delta):
    get_mouse_position()
    calculate_angle()
    level()
    calculate_torque()

# Check to see if the mouse is in the deadzone and if not we set a value to the mouse_input.
func get_mouse_position():
    var mouse_pos = get_viewport().get_mouse_position()

    if deadzone.has_point(mouse_pos):
        mouse_input = 0.0
        return

    if mouse_pos.y > deadzone.position.y:
        mouse_input = 0.05
    elif mouse_pos.y < deadzone.position.y:
        mouse_input = -0.05

# Calculate the angle of the RigidBody.
func calculate_angle():
    var flat_forward = get_global_transform().basis.z
    flat_forward.z *= 1
    flat_forward.y = 0

    if flat_forward.length() > 0:
        flat_forward = flat_forward.normalized()
        var local_flat_forward = to_local(flat_forward)
        box_angle = atan2(local_flat_forward.y, local_flat_forward.z)

# If the mouse is not providing any input, we want to level out the RigidBody by applying
# an opposing force until it's equal.
func level():
    if mouse_input == 0.0:
        mouse_input = -box_angle

# Add the torque to make the RigidBody move.
func calculate_torque():
    var torque = Vector3.ZERO
    torque += mouse_input * get_global_transform().basis.x
    add_torque(torque)


texts:
I'm having real trouble resolving this issue with triangle-convex hull SAT test intersection.

The problem is as follows:

Misses are detected accurately enough:

Clear miss

I have not found a problem with false negatives (ie collision is there but not detected).

But I do have a problem with false positives (collision detected even though there is not one)

Appears to detect false +

This only happens occasionally with orientations like the one shown (that is actually a pretty big gap).

What I'm doing conceptually is just a usual SAT test for the triangle against the hull.  I'm pretending the single triangle is a "convex hull", indeed it might be if you imagine it is a very thin, very flat tetrahedron.  I don't know if I am mistaken in this concept of triangle-convex hull intersection, if the slight inaccuracy is to be expected, or if there is perhaps a bug in my code (the same SAT Test routines work for hull-hull, box-hull, and other test quite accurately though)

The relevant code is at line 621 of hull.h, with the SATTest overlap routine in Intersectable.cpp.


texts: Turn Based Game - Best approach for Server communication. TCP/IP or REST API?

texts:
I want to create a turn base multiplayer game where each player simultaneously takes his/her actions, and ends the turn. Both will see what the other player did afterwards and the next round begins.

Think of it as some kind of chess, but both players take turns at the same time without seeing it until both end their turn.

I though about a server software that creates direct TCP/IP connections to both players and communicates the necessary stuff like what the other player did, who lost/won ect. The usual stuff.

But thinking of TCP/IP port limitations this could mean a limitation of about 65000+ users per server? Meaning 32500 active matches per server?

Then I thought about some kind of dispatcher. Like a REST API server that generates a unique game id and all players call the service with their ID (e,g transferring everything with JSON or some binary data).

I am not quite sure which approach is the better one. Maybe I am wrong at some point? Running a background service for each match seems to be my approach for both solutions (GameManager Class instance creation or a new process gets started communicating via named pipes or localhost). Maybe someone has some experience with this or another great idea? :)


texts: What's the most efficient way to send a users keypresses to the server?

texts:
So I've been coding a little project in JS recently, using node.js and socket.io to create a server, and HTML5 canvas to draw the client side. The user receives info from the server every 20ms, and the client interprets the data and displays it. If the user presses a key on the keyboard, it stores this information and sends it to the server instatly - so currently, the code is basically 'is keyboard pressed? if yes, send data to server'.

This has all worked great so far, however recently I increased the servers enemies (AI objects) from only 10 to a whopping 100... this lagged the server. Although I will work out enemy spawning efficiency later, the problem that immediately became apparent is that the user's character moved slower when the server was lagging. This meant that chasing enemies were able to easily catch up to the character and kill him, whereas usually the character could run away with relative ease.

This leads me to the question, what is the most efficient way that the server can interpret the keypresses of the user, and ensure that even if it is lagging that enemies will move at the same proportional speed to if the server wasn't lagging.

Sorry if this question is long-winded, any advice or help would be greatly appreciated. I assume that the same methodologies should apply from different coding languages, so if you have a vague idea how it works in a language you've used... please still share! :)

Thanks,

Cameron


texts:
I'm working on a project that remakes mario 3 (NES). In my game loop, i face a strange thing. Here is my code:

 while (true)
{
    if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
    {
        if (msg.message == WM_QUIT)
        {
            break;
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else
    {
        //Game logic
        c1++;
        _Mario.Update(1.0 / FPS);

        //Render
        _Timer.SetBeginTick();
        _LpD3dDevice9->Clear(0, 0, D3DCLEAR_TARGET, D3DCOLOR_XRGB(102, 255, 255), 1.0f, 0);
        if (_LpD3dDevice9->BeginScene())
        {
            c2++;
            _Mario.Render();
            _LpD3dDevice9->EndScene();
        }
        _Keyboard->GetState();
        _Mario.Move(_Keyboard);
        _LpD3dDevice9->Present(0, 0, 0, 0);
        _Timer.SetCurrTick();
        _Timer.UpdateGameTIme();
        if (_Timer.ElapsedTime < (1.0 / FPS))
        {
            Sleep(1000.0 / FPS - _Timer.ElapsedTime * 1000);
        }
    }
}

Update function :

void ImageMove::Update(float t)
{
    _Image_X += _Image_Vx * t;
    _Image_Y -= _Image_Vy * t;
    _SpriteTimer.SetCurrTick();
    _SpriteTimer.UpdateGameTIme();
    if (_SpriteTimer.ElapsedTime >= 1.0 / ANIMATE_RATE)
    {
        if (_Image_Vx > 0) _Image_Right.Next(); //change to next sprite
        if (_Image_Vx < 0) _Image_Left.Next(); // change to next sprite
        _SpriteTimer.SetBeginTick();
    }
}

Render Function :

void ImageMove::Render()
{
    int vpx = _Image_X - 400;
    int VIEW_PORT_Y = _Image_Y + 500;
    _SpriteHandler->Begin(D3DXSPRITE_ALPHABLEND);
    if (_Image_Vy > 0 && _Image_Vx_Last > 0) _Image_Jump_Right.Render(_Image_X, _Image_Y);
    else if (_Image_Vy > 0 && _Image_Vx_Last < 0) _Image_Jump_Left.Render(_Image_X, _Image_Y);
    else
    if (_Image_Vx > 0)_Image_Right.Render(_Image_X, _Image_Y);
    else if (_Image_Vx < 0)_Image_Left.Render(_Image_X, _Image_Y);
    else if (_Image_Vx_Last < 0)_Image_Left.Render(_Image_X, _Image_Y);
    else _Image_Right.Render(_Image_X, _Image_Y);
    _SpriteHandler->End();
}

I put c1 and c2 in my game loop to measure how many times Update and Render are called. I set fps = 60, while debuging, I let my game loop run for 5s, then set a breakpoint to view c1 and c2. The value of c1 = 320, and c2 = 160 ( = 1/2 c1 for sure, i have run it many times, so the times render is called only ~1/2 fps, i think with fps = 60, it should be ~300 for 5s, shoudn't It?).

If i debug with F10 (on Visual studio) , I can see a loop will execute with _LpD3dDevice9->BeginScene() success, and _LpD3dDevice9->BeginScene() in next loop always failed.

Is it error? Because i have tested on another small project, and c2 = 1/2 c1 too.
This problem cause an issue in my game. In Update() function, I change my sprite here, and draw it in Render() , so I always miss some sprite. Because It only render = 1/2 time game update.

If it is an error How can I fix my game loop? And if It is not an error, what can I do to prevent missing sprites?

P/S : sorry for bad English.


texts: Unity Capture And Display Live Camera Feed

texts: I want to display the video using the device camera on specific part of the screen on iOS, android and Editor. I was able to find the WebCamTexture which display the camera video on the Quad (3D Object). Now I want to record the video and save it on the disk. Is there are way to do that ? Or is there a better way to do that using unity or through plugin ?


texts: Best approach to implement server authority in client/server game

texts:
I am currently trying to create a 2D game with a client/server model, and was wondering how I could implement the server's authority over the client (when client moves, prediction happens, and server checks if the prediction was well done, and if not, client reverts to older state).

Should I create a State class where the local player's state is saved at every tick in a buffer, for revert being possible ? Or should I wait for the server to respond and should the client be a simple renderer ?

How could I make sure that client and server are synchronized ?

I use pure java Socket class as well as DatagramSockets.


texts: What is the default audio bitrate in Unreal 4?

texts: Maybe I'm just googling the wrong thing but what's Unreal's default audio sample rate? 44.1kHz or 48kHz? Silly simple question but thanks for helping out!


texts: Hinge joint is not firm, leaving connected anchor position

texts:
I have a hook with hinge joint which is working fine but as my object quickly move my hook leave its position for a while.

And here is the hinge joint settings with rigidbody:

Here is a short clip of the problem.


texts: How to make a tile that can be stretched out

texts:
I was playing angry birds and I saw that the elastic used to throw the birds is a texture that expands well when you push it with your finger.

How can textures like this be made in java with libgdx? What are the techniques used in cases like this?

I am asking this because it is obvious that in this situation they did not used a bunch of tiles to make an animation and I have no idea how it is made.

Thanks


texts: How do I get started with fog type effects in a first person game?

texts:
Hey guys, I'm currently using JME3 to learn 3d game development in java, and I have run into a situation. I would like to add fog effects to my games, but I don't even know where to start to implement this. I know how to set the camera's far frustum to limit the render distance, but that just simply makes a sharp cutoff. I'd like the fog it up a bit to make it feel more natural.

I'm looking for an answer that points me into the correct direction. I'm not looking for specific code snippets or even JME3's engine specifics. I just want to get an idea of how this stuff works in general.

Thanks!


texts: Should I use Async & Await, instead of Coroutines, in Unity?

texts: Should I use Async & Await in Unity?  Or should I keep using Coroutines?  If I should use Async & Await, how can I do so in a manner comparable to Coroutines?


texts: Is it safe to set FPS rate to a constant?

texts:
I learned from game class that in update function, every movements must be time dependent for the sake of linearity in movement.

We made a simple game. Every move like going left, right or jump is written time dependent.

But, in some other computers, our game is worked very differently. For example, our character jumps higher than it should be. I guess this is because each computer has different FPS rate according to its specification.

My question is that what should we do to make this game work in same way in every computer? Setting FPS rate to a constant is a solution?


texts:
I'm writing a little something in libgdx to learn more about the platform. Currently, I have a simple generated world consists of tiles, which are just blocks of texture drawn to the screen. It's a simple setup, but I'm wondering how would I go about switching to a different "scene". For instance, just imagine a player, walking around in a grass field, enters a cave, and bam, he is in the cave. The world behind him has transitioned from a grass field to a cave (essentially, from one generated world to another).

I'm not very sure how libgdx handles scenes, so if anyone can share some tips, I'd appreciate it.

NOTE: I know this is a very broad question; right now I'm not asking for a specific solution but rather some tips to help me approach the idea I'm going after.


texts: Rain Effect generation in a Unity VR project

texts:
I´m developing a VR project in Unity Engine and I need to implement a Rain Effect. I have considered the following:

A VR game must run at least 90 frames per second.
The Rain must be detailed.
The Rain Drops interact with other objects.

These are the approaches I have considered:

Particles Systems: I think it is expensive since there are two cameras rendering the scene and checking collision per particle could be expensive.
Image Effect on the canvas: I think the result would be unreal, and there would not be interaction with other objects.

I have seen examples of rain effect like in Resident Evil 4, Halo Reach, Crysis, FarCry, Project Cars 2 VR and Batman Arkham Knight.

A last approach I haven´t considered yet is by shading, maybe shading would work for the rain drops in the cameras´ lens.

I would like to know optimal approaches to emulate rain effects without making too much computations.

Thanks for your attention.


texts: Why are games using interpreted languages instead of compiling code into libraries and calling them at runtime?

texts:
Say I want to include a game mechanic where players are invited to code up some algorithm to control robots which would defeat the enemy and protect the tower efficiently. Most games I've seen to implement something like that, support Lua. But what if they accepted a .Net compiled library with implemented in C# (or Java for example) interfaces, essentially doing the same thing? How is it a better or a worse choice?

Code may (not) compile in either case. Some players may (not) be familiar with one of the languages. The computer may not have .Net (or Java) framework installed (but then the game usually comes with at least some redistributable packages, so it may as well include those too). These obvious arguments go either way. Is there some important reason that interpreted languages are the norm, and not compiled which I'm not aware of?


texts: 2D Car Simulation with Throttle Linear Physics

texts:
I'm trying to make a simulation game for an automatic cruise control system. The system simulates a car on varying inclinations and throttle speeds.

I've coded up to the car physics but these do note make sense.

The dynamics of the simulation are specified as follows:

a = V' - V

T = (k1)V + θ(k2) + ma

V' = (1 - (k1 / m) V) + T - ( k2 / m) * θ

Where

T = throttle position
k1 = viscous friction
V = speed
V' = next speed
θ = angle of incline

k2 = m g sin θ
a = acceleration
m = mass

Notice that the angle of incline in the equation is not chopped up by sin or cos.
Even the equation for acceleration isn't right.

Can anyone correct them or am I misinterpreting the physics?

Source: "scribd.com/doc/105335356/124/INDUSTRIAL-APPLICATIONS"; Page 508. Number 13.2.


texts:
I am an absolute beginner with game programming, should this question be poorly formulated, be aware it was not sloppiness by my side, but lack of game programming experience.

The game I am planning to code will use a top-down 2D map as "world". The world might be larger than the window (the window can zoom in or out) and the vehicles can be located at any point of the world (= it's not a tiled map, the space is "continuous").

To clarify with an example: if the world is a terrain of 1000x1000 metres, a vehicle could be at location (327.31, 720.4) metres.

My question is: what is the most convenient way to represent the world internally? I could think to these possibilities:

do nothing and use metres as if I were working with the physical object,
normalise to pixels defining the world size as the number of pixels for representing 1000 metres at maximum zoom,
normalise to 1 defining the word as a square of size 1

...but I am sure there might be some other ones / some of mine could make no sense. It's just that being my first game I don't have a clear pictures of the problems ahead of me, and I would like some guidance in making a reasonably correct initial choice.

Thank you for your time.


texts: Why does my Window take a few clicks to actually close even though the event fires?

texts:
I am pretty new to game dev (and libgdx + scene2d specifically), I am creating a dialog system for an rpg game and obviously a dialog window has a close button to close a dialog but for some reason it takes few clicks to close it (see video).

I have added System.out.println(Actor.class) to where the listener executes:

As you can see the events fired as planned!

Here is my listener code:

closeButton.addListener(new ChangeListener() {

  @Override
  public void changed(ChangeEvent event, Actor actor) {
    System.out.println(Actor.class);
    event.getListenerActor().getParent().addAction(Actions.hide());
  }
});

Please send help,  thank you


texts:
I work on a little project, and in the past, I used SpriteManager : DrawableGameComponent as my SpriteManager class.

I have been told that DrawableGameComponent is not so recommended to use, so I decided to make my own custom methods in a new class called SpriteManagerGeneral. Now I try to acces that class via Game. In the past I used this in Game:

spriteManager = new SpriteManager(this);
Components.Add(spriteManager);

But now I can't do this with SpriteManagerGeneral because it's not a GameComponent.

Do I just change my class (and edit my methods) to SpriteManagerGeneral : GameComponent or is there another way (that is better than GameComponent) to do this?

NOTE: I'm a beginner in programming.

NOTE2: Yes I know why DrawableGameComponent is not so recommended.


texts: How to hide a post-processed mesh outline when/where the mesh is hidden

texts:
I'm working on setting up an active outline in my 3d engine, a highlight effect for selected 3d characters or scenery in the screen. After working with the stencil buffer and getting some unsatisfactory results (issues with concave shapes, outline thickness due to distance from camera, and inconsistencies between my desktop and laptop), I switched to edge detection and frame buffer sampling and got an outline I'm pretty satisfied with.

However, I am not able to hide the outline when the selected mesh is behind another mesh. This makes sense given my process, since I simply render 2d shader outline from a frame buffer after rendering the rest of the scene.

Two screen captures of my results are below. The first is a "good" outline, the second is where the outline is seen over a mesh that blocks the outline source.

The rendering process runs like this:
1) Draw only the alpha of the highlighted mesh, capturing a black silhouette in a frame buffer (framebuffer1).

2) Pass the texture from framebuffer1 to a second shader that performs the edge detection. Capture edge in framebuffer2.

3) Render the entire scene.

4) Render the texture from framebuffer2 on top of the scene.

I have a few ideas on how to accomplish and am hoping to get feedback on their validity, or on simpler or better methods.

First, I've thought of rendering the entire scene to a frame buffer and storing the visible silhouette of the highlighted mesh in the alpha channel (all white save where the highlighted mesh is visible). I would then perform the edge detection on the alpha channel, render the scene frame buffer and then render the edge on top. Resulting in something like this:

To accomplish this, I thought of setting a define only during the render pass of the highlighted object that would draw all black in the alpha for any visible pixels.

My second idea is to use the current render process outlined above, but also store the X, Y and Z coordinates in the R, G and B channels of framebuffer1 when rendering the silhouette of the selected mesh. Edge detections would be performed and stored in framebuffer2, but I would pass on the RGB/XYZ values from the edges of the alpha to the silhouette. Then, when rendering the scene, I would test if the coordinate is within the edge stored in framebuffer2. If so, I would then test the depth of the current fragment to determine if it is in front of or behind the coordinates extracted from the RGB channels (converted to camera space). If the fragment is in front of the depth coordinates, the fragment would be rendered normally. If the fragment is behind, it would be rendered as the solid outline color. This seems like a more convoluted and error prone method...I haven't fully grasped packing and unpacking floats in OpenGL yet, but my feeling is I may run into floating point precision issues when trying to store the XYZ coordinates in the RGB channels.

I'm using LibGDX for this project and would like to support WebGL and OpenGL ES, so none of the solutions involving geometry shaders or newer GLSL functions are available to me. If anyone could comment on my proposed approaches or propose something better I'd really appreciate it.


texts: OpenGL: What's the best way to convert a screen coordinate to a world coordinate?

texts:
For example, suppose I'm building a first-person shooter and the player pulls the trigger. I want to convert the screen coordinate (x, y) into a world coordinate (x, y, z) to know what they've hit.

I've seen some people mentioning a lookup using glReadPixels, but I've heard it's slow and those references were years old, so I'm not sure if this is the best way.

I'm working with core OpenGL 3.3, not ES. gluUnProject is not part of the API I'm asking about.

These types of answers would be most helpful:

An explanation of how to retrive a pixel's (x, y, z) value using glReadPixels and how to transform that into world coordinates. I know how to multiply by inverse matrices; I don't know exactly what steps OpenGL takes to arrive at its depth buffer value.
Or, an explantion of how to do something similar, perhaps more efficiently, with a pixel buffer object.
Or some method that I don't even know about that's better than either of the above.

For some context: I have many months' worth of code into a game I'm developing in OpenGL using the core 3.3 profile. I'm using minimal libraries and not the old fixed-function GL pipeline, which is why it does not make sense for me to use gluUnProject. I mention this to highlight why this question is not the duplicate of a currently-linked older question.

Note: I previously mentioned a shader idea that did not add much to the question, so I removed it. I also edited the question to clarify the context and the type of answer I am looking for.


texts: How to construct the marching cubes tables algorithmically?

texts:
I want to implement the marching cubes algorithm from scratch, but I'm stuck at the polygon generation phase (building edge loops with correct orientation and triangulating them).
Obviously, I should consider all 2^8 = 256 cases, find out zero-crossing edges (build 12-bit edge masks) and figure out the triangulation in each case.

Could you please give me some ideas on how to correctly construct and triangulate edge loops?

I'd like to avoid considering each MC configuration (out of 15) separately as it seems somewhat tedious and messy to me.


texts: Changing the origin/pivot point of the parent in Unity

texts:
I create a game object, add some children to it, and would like the pivot point of the parent to be somewhere inside the area occupied by the children, not far away in the scene.

Like in the example below, I have three blocks of platforms situated near each over. I add them into a parent, then try to move that parent and notice that the origin point of the parent is actually not somewhere between its children, but outside them on the upper right:

Does someone know a way to change the origin point in such case?


texts: how to move the rect transform by mouse drag

texts:
I am trying to do a slider in the UI with the mouse, I want to move the rect transform right side when I drag the mouse right and vice-versa.

I tried but it didn't work please help me thanks in advance!!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class slide : MonoBehaviour {

Vector3 prevpos = Vector3.zero;
Vector3 posdelta = Vector3.zero;

float xRotation = 0;
float zRotation = 0;
public RectTransform controllerposition;
public GameObject lastposition;

float speedFactor = 0.04f;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        prevpos = Input.mousePosition;
    }

    if (Input.GetMouseButton(0))
    {

        posdelta = Input.mousePosition - prevpos;

        Vector3.Distance(controllerposition.transform.position, lastposition.transform.position);
        {
            controllerposition.DOAnchorPos(new Vector2(-100, 0), 0.25f);

        }

    }

    prevpos = Input.mousePosition;
}

}


texts: Detect which tile in a tile palette a player is colliding with

texts:
I have a megaman-style platformer that I've been working on for a while now. I'd like to have my scene set up so that when a player interacts with certain tiles, it will have some sort of effect on the player.

This could easily be achieved with creating individual sprites for the aforementioned interactables, but I'd ideally like to be able to have a portion of my script handle it so that everything besides the player and enemies would be tilemaps.

For instance, I have a tile that would act as a treadmill that moves the player along in one direction. Another tile would be bouncy, and another would deal damage.

I have the game set up right now to detect when the player is touching a tile, but I have no way of being able to tell which tile the player is touching. Is there a way to be able to compare programmatically which tile from a tile palette my player's hitbox is currently touching?


texts: Assistance with bomb throwing mechanics akin to Zelda 2D

texts: Does anyone have a good algorithm for managing the carrying and throwing of bombs? I've attempted to find a tutorial and can't find anything that covers the subject matter. I'm just looking for a very high-level algorithm; the coding I can handle.


texts: How can I evaluate varying conditions in a Scriptable Object?

texts:
I'm new to using Scriptable Objects, so this might just be a bit of confusion.

Let's say we have a Scriptable Object that defines the abilities a character might have in the game, and a character class that triggers these abilities:

public class Ability : ScriptableObject
{
    public string Name = "New Ability";
    public int ManaCost = 10;
    public Sprite AbilitySprite;

    public void Execute(ref Character character)
    {
        if (character.Mana < ManaCost)
        {
            return;
        }

        // Do something, like instantiating and moving the sprite

        character.Mana -= ManaCost;
    }
}

public class Character : Monobehaviour
{
    public int Health = 100;
    public int Mana = 100;

    public List<Ability> AbilityList = new List<Ability>();

    private void Update()
    {
        // Crude implementation for example purposes
        if (Input.GetKeyDown(KeyCode.Alpha1)) Abilities[0].Execute(ref this);
        if (Input.GetKeyDown(KeyCode.Alpha2)) Abilities[1].Execute(ref this);
    }
}

Obviously we can make numerous abilities with different mana costs, and add them to each character in the scene as needed; some characters may have a "Bolt" ability, while others might have an ability that casts "Fire." The Execute() method will then evaluate whether or not the character can use these ability based on the character's current mana.

But what if some of these abilities, all of which have similar effects, needed to also check the character's health, or perhaps a collision state, like isGrounded? For instance, maybe a certain ability can only be executed when the character has the appropriate mana value, and is also airborne. Would it be necessary to make many different subclasses of the Ability class to accommodate these different conditions, each with its own logic?

At first I tried changing the Execute() method to take in a bool, like this:

public void Execute(ref Character character, bool canExecute)
{
    if (!canExecute || character.Mana < ManaCost)
    {
        return;
    }
}

The problem with this is that I have to hard code the conditions for canExecute and compare the current ability against its Name, and that sort of defeats the purpose of Scriptable Objects. My goal is to be able to create abilities that might need to check varying conditions while performing the same functionality, and assign them in the inspector to each character as needed.


texts:
The first approaches in animation for my game relied mostly on sine and cosine functions with the time as parameter.

Here is an example of a very basic jump I implemented.

if(jumping)
{
    height = sin(time);
    if(height < 0) jumping = false; // player landed
    player.position.z = height;
}

if(keydown(SPACE) && !jumping)
{
    jumping = true;
    time = now(); // store the starting time
}

So my player jumped in a perfect sine function. That seems quite natural, because he slows down when he reached the top position, and in the fall he speeds up again. But patching every animation out of sine and cosine is stretched to its limits soon.

So can I improve my animation and provide a more abstract layer?


texts: Bullet physics C# script Is imparting force on rigidbody objects

texts:
I have recently made the simplest gun and bullet script that I could and it works amazingly, except for one problem that I've found. When I attach it to a game object with a rigid body the force of the bullets move the object back with quit a bit of force.

But what I can't seem to figure out is why the bullets are imparting force on the object at all. The bullets do not have a rigid body component. The way my guns work is with two scripts, one which acts as a simple spawning point when a key down event is given and what ever object you give it to spawn.

The second script is applied to the bullet itself which causes the bullet to have motion through transform.Translate with a speed variable. The best example I can give of this is when I attached two guns to the default unity jet and when I fired, it had enough force to move the jet back against its thrust speed.

I really would appreciate any help with this so I can move on with my project. I will provide the code bellow for the two scripts.

Thank you

public class Shoot : MonoBehaviour {
  public GameObject bullet;

  void Update () {
    if (Input.GetKey (KeyCode.Mouse0))
      Instantiate(bullet, transform.position, transform.rotation);
  }
}

public class MoveBullet : MonoBehaviour {

  public float speed = 1f;

  void Update () {
    transform.Translate (0, 0, speed);
  }
}