texts: Should each Entity have its own update and render methods?

texts:
First, the questions:

Should each Entity (which are classes like Character, Tree, Enemy) have its own update() and render() methods?
If that's the case, then should I use Interfaces like "Renderable" and "Updatable"?

I ask you this because most of the tutorials I followed "told" me to include all Input Handling and Updates inside the Game's main update() method, and all the Rendering inside the Game's main render() method.

I know these tutorials are very simple but even a few more complex ones still had all the Entities' actions inside the same block of code, which made me doubt the ideas I previously had (separating updates and renders per each object).

To clarify, I feel like I should have something like this:

update() {
    HandleTheUserInput();
    for each active Entity in the game right now {
        entity.update();
    }
}

Then, the same thing for rendering (except the input part). Am I following the right path here or should I rethink the current architecture ideas I have? Thank you.


texts:
I have a problem that bugged me for quite some time now
I'm trying to Install Ubity3d on Ubuntu
I Followed some instructions that i've found after some research
I downloaded and installed UnityHub and the latest release (UnitySetup-2019.1.0f2) that i found on Unity on Linux: Release Notes and Known Issues

and i moved the installed unity file from Home to opt folder and made it run on command unity3d and here is what i did exactly

sudo mv Unity-2019.1.0f2 /opt/Unity3D
sudo ln -s /opt/Unity3D/Editor/Unity /usr/bin/unity3d

and the problem is that every time i open Unity editor (via both the command line and UnityHub) the unity Launcher appears for moments to proccess and then crashes and the editor doesn't open and the error changes everytime i try to open the program here are 3 forms of errors that appeared to me, here is the first

Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
[Unity Package Manager (Upm)]
Parent process [5258] was terminated
Segmentation fault (core dumped)

and the second

Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
(unity-editor:6651): Gtk-CRITICAL **: gtk_file_chooser_widget_set_current_name: assertion 'priv->action ==
GTK_FILE_CHOOSER_ACTION_SAVE || priv->action ==
GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER' failed
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
[Unity Package Manager (Upm)]
Parent process [6651] was terminated
Segmentation fault (core dumped)

the third is

Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
[0616/110743:ERROR:browser_main_loop.cc(161)] Running without the SUID sandbox! See
https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment for more information on developing with the sandbox on.
[0616/110744:ERROR:browser_main_loop.cc(207)] Gtk:
gtk_window_present_with_time: assertion 'GTK_IS_WINDOW (window)' failed
ATTENTION: default value of option force_s3tc_enable overridden by environment.
USER@USER:~$ [Unity Package Manager (Upm)]
Parent process [7583] was terminated

and stuck on that....
well i know that there's something wrong with GTK but i have no experiace with it and i didn't find anything useful on this matter on google

  OS: Ubuntu 16.04 LTC


texts:
I am writing a simple game where some things happen after some amount of time. I used simple time analog of the framework I use to schedule these events, however, I have found that I will not be able to pause the game because the time is continuously increasing and nothing can stop it. So I decided to have my own time which is updated each update() function call to a delta time (example in Lua):

current_time = 0.0

function update(dt)
    current_time = current_time + dt
end

So I am able to pause the game now by simply not incrementing the game time and not doing anything at all (simply return from the update function). The question is do I do this correctly? Does every game engine do this this way? I just could not think of any other method for implementing game time with pausability.

P.S. update function is called in the game loop on each iteration. The fps is locked to a constant.


texts: How do I compile further libraries into my game?

texts:
This might be vague; I don't know how to search for this.

How do I link a GUI framework (in my case, CEGUI) to a graphics framework (in my case, SDL)?

I'm using a Mac. My mental model on how to add libraries is something like this in my head:

  There are .framework files. They go in /Library/Framework/. You then link them to Xcode in build settings, then they magically work. Then there are libraries you add to header path, and library path and something about include and lib folders, but I don't understand those.

A guide from the ground up would help, because I would like to get a better understanding of how it works. I also have no idea what cmake is, although I've been seeing it a lot.


texts: Pathfinding on a uneven planetary surface

texts:
My question is what would be the best approach to pathfinding on an uneven planetary surface?

Background Information

I have created a planet from displacement mapping 6 sphere projected planes. The planes initially formed a cube before being projected into a sphere shape.

I'm wondering if it is possible to use each "sphere projected cube face" as grids and use a simple A* algorithm to find the best possible route, I would also like the displacement height to be taken into account so the path avoids climbing mountains etc (I guess this would just be a heuristic within the A* algorithm)
Another consideration is that I have achieved planetary movement by leveraging Unity3d's physics engine, apply gravity towards the centre of the planet. Would my proposed solution require the agents movement to be controlled independently to gravitational physics.

To help better articulate my question this is my current planetary body:


texts: bug in webgl phong shader: lighting rotates with object

texts:
I'm working on a simple phong shader in webgl, and I think I'm getting close but something is still wrong. Dead give away: if I have a billboard and have it roll (so it spins like a wheel), the part of the billboard that is lit up spins with it :(.  This confuses me, because it seems like a problem with the model matrix, but the transform makes all the positions & rotations correct, and lighting math is done entirely in world-coordinates , just the lighting wrong.  Ditto with the view matrix, I can move around and look freely and everything is located in its proper place, just lit wrong.

Here are my shaders (minus the definitions for space, and with the lighting in the model matrix moved into GPU for clarity)  {if you prefer reading in github: https://github.com/nickgeorge/quantum/blob/master/index.html#L41}

<script id="fragment-shader" type="x-shader/x-fragment">
  void main(void) {
    vec3 lightWeighting;
    if (!uUseLighting) {
      lightWeighting = vec3(1.0, 1.0, 1.0);
    } else {
      vec3 lightDirection = normalize(vLightPosition.xyz - vPosition.xyz);

      float directionalLightWeighting = max(0.0, dot(
          normalize(vTransformedNormal),
          lightDirection));
      lightWeighting = uAmbientColor + uPointLightingColor * directionalLightWeighting;
    }

    vec4 fragmentColor;
    if (uUseTexture) {
      fragmentColor = texture2D(uSampler,
          vec2(vTextureCoord.s, vTextureCoord.t));
    } else {
      fragmentColor = uColor;
    }
    gl_FragColor = vec4(fragmentColor.rgb * lightWeighting, fragmentColor.a);
  }
</script>

<script id="vertex-shader" type="x-shader/x-vertex">
  void main(void) {
    vPosition = uModelMatrix * vec4(aVertexPosition, 1.0);

    // TODO: Move back to CPU
    vLightPosition = uModelMatrix * vec4(uPointLightingLocation, 1.0);

    gl_Position = uPerspectiveMatrix * uViewMatrix * vPosition;
    vTextureCoord = aTextureCoord;
    vTransformedNormal = normalize(uNormalMatrix * aVertexNormal);
  }
</script>

Thanks a lot, and let me know if there's anything else useful to add.


texts: How to produce interreflections in Unity3d?

texts:
Notice how the "door" shown below appears multiple times in the reflections, both vertically and horizontally. These "extra" reflections are called interreflections. I am trying to reproduce this effect in Unity3d.

There are docs for interreflections, but following the provided steps does not produce any additional reflections. I spoke to a few others who also had a similar problem--it seems that increasing the bounce count alone does not produce interreflections.
So how can I do it? What are the additional steps required to do this? Is this effect not called an interreflection? If so, what is it, and how can I produce it?


texts: Collisions between two objects in 2D space

texts:
I am implementing the collisions of my game in javascript, and at the moment what happens when the objects collide is that they have their speed changed to 0. What I'm starting to want to do is to make it a little more interesting when the player plays with other objects in motion, they collide and separate. This is a very physical 2D issue itself.
If an object A is at positive velocity at x collides with an object B is at negative velocity at x, collide head-on, what would be the best calculation to do so that they separate naturally after the collision?

What if they go in the same direction in x? and if one has going on x and another on y? How do I deal with all this?

Should I add mass and acceleration to make this separation calculation after the collision?


texts: Change the color of GL.wireframe in Unity

texts:
Need to render something with GL.wireframe, this is what I have at the moment.

void OnPreRender() {
    GL.wireframe = true;
}
void OnPostRender() {
    GL.wireframe = false;
}

However the wireframe rendered is black and this will not work for my game. I've tried adding the following to OnPreRender()

GL.Color (Color.red);

Unfortunately the wireframe remains black. Does anyone know the proper way of changing this color?


texts: Why aren't game mods allowed to talk to the outside?

texts: Sorry if the title is a bit obscure, I didn't know what to call this. I recently got into mod making and thought of a mod which is able to control Spotify through in-game commands, using Spotify's API to do so. However, most of the games I found which support mods (WoW through addons and Skyrim and Fallout 4 through Creation Kit) don't allow you to perform requests or even communicate with external applications. I wanted to ask why game developers perform this practice, specifically what problems can arise if the user is permitted to perform requests through the internet or communicate to external applications?


texts: Most efficient way to handle coordinate maps in Java

texts:
I have a rectangular tile-based layout. It's your typical Cartesian system.

I would like to have a single class that handles two lookup styles

Get me the set of players at position X,Y
Get me the position of player with key K

My current implementation is this:

class CoordinateMap<V> {
    Map<Long,Set<V>> coords2value;
    Map<V,Long> value2coords;

    // convert (int x, int y) to long key - this is tested, works for all values -1bil to +1bil
    // My map will NOT require more than 1 bil tiles from the origin :)
    private Long keyFor(int x, int y) {
        int kx = x + 1000000000;
        int ky = y + 1000000000;
        return (long)kx | (long)ky << 32;
    }

    // extract the x and y from the keys
    private int[] coordsFor(long k) {
        int x = (int)(k & 0xFFFFFFFF) - 1000000000;
        int y = (int)((k >>> 32) & 0xFFFFFFFF) - 1000000000;
        return new int[] { x,y };
    }
}

From there, I proceed to have other methods that manipulate or access the two maps accordingly.

My question is... is there a better way to do this? Sure, I've tested my class and it works fine. And sure, something inside tells me if I want to reference the data by two different keys, I need two different maps. But I can also bet I'm not the first to run into this scenario.

Thanks!


texts: Can a 4x4 matrix describe a camera's perspective?

texts:
I'm working with a closed-source 3D engine, and it only allows you to set the view projection via a 4x4 matrix. Can this matrix describe the camera's translation, rotation & perspective?

I turned perspective on/off in the engine using a function call, and the matrix values are as follows.

Without perspective:

1   0   0   -0.0559203194265751
0   1   0   -0.0251115292255206
0   0   1   -0.016129
0   0   0   0.0926626011715394

With perspective:

1   0   0   -0.0560158276396793
0   1   0   -0.0251013526176432
0   0   1   -0.016129
0   0   0   0.0308875337238465


texts: How can I find the valid words in a grid of characters?

texts:
I am creating a game similar to Tetris, with two main differences: the screen already begins filled with tiles (like in Puzzle Quest for Nintendo DS and PC) and each individual tile has a letter in it. The player's objective is to eliminate tiles by forming valid words with them. Words are formed by placing letters next to each other, in any direction, except diagonally.

The player can move an entire row of tiles to the left or to the right or an entire column of tiles up or down, for as many spaces as he desires (if the movement of a row/column surpasses the limits of the board, the letter that crosses the limit will "cycle", appearing at the other end of the row/column). After the player's action, the game should check the entire board to look for valid words and remove the letters that form those words from the board. The letters above those that were removed will fall down in the place of those letters that were removed and new letters will drop from the top of the screen until the board is filled up again.

I have already written a linear algorithm that, given a sequence of characters, determines if it is a valid english word. The problem I am having is: how can I check for valid words on the board? Is brute force the only way? Testing all possible combinations from the board to see if they are valid is very slow, even for a small (5x5) board. Any help will be very appreciated, thanks!


texts: How can I create animated card graphics like in Hearthstone?

texts:
In the game Hearthstone, there are cards with animated images on them. A few examples:

http://www.hearthhead.com/card=281/argent-commander
http://www.hearthhead.com/card=469/blood-imp

The animations seem to be composed of multiple effects:

Particle systems.
Fading sprites in and out/rotating them
Simple scrolling textures
A distortion effect, very evident in the cape and hair of example 1.
Swirling smoke effects, the light in example 1 and the green/purple glow in example 2.

The first three elements are trivial, what I'd like to know is how the last two could be done. Can this even be done realtime in a game, or are they pre-rendered animations?


texts: What is the right approach for using foot ik for characters in slopes(Specially when in walk or run)?

texts:
i use unity but this question applies for any third person controller or enemy controller.
i need to use foot ik on slopes(any condition and any kind of slope) to place foot on right places. as i considered some important third person games, it seems they only use ik when character is idle and not moving otherwise no ik is applying and leg animations run purely.
i use the same approach and result looks good enough but im looking for applying when character is walking or running.
as i looked, some people disable ik when leg is going up and enable it when its coming down. some other do a raycast from foot bone to the ground to check foot need ik on little distance to ground. but all of these are prototypes and has flaws. can you give me a good approach that works best in all conditions?


texts: Efficient 2d Java Line of Sight for a lot of entities?

texts:
My problem today is this:

I have many civilians going around, they are classes stored by an arraylist.

The idea is when they see another civilian panic, they'll start to panic and it will spread.

First I call each classes Step() function by looping through an iterator. Then in the Step() function it goes through another civillian iterator
     As it goes through, it tries to detect whether it can see the other civillian in the iterator, this is where performance time goes from 0 to 50 Milliseconds for having 100 Civillians.

This is the problem I need to fix, I tried to make an easy way to detect whether any objects are in the way of point a to point b.

Here's the code for the line of sight:

public static Object LOS(int x, int y, int x2, int y2, String Scan, Object Me, Object You) {
   DirectionX = (x-x2)/Quality;
   DirectionY = (y-y2)/Quality;
   CurrentX = x;
   CurrentY = y;
   String[] ScanArray = Scan.split(":");
   for(int I=0;I<=Quality;I++) {
      for(String Type: ScanArray) {
         if(Type.equals("Boxs")) {
            Iterator it=Level.Boxs.iterator();
            while(it.hasNext()) {
               Box Box = (Box)it.next();
               if(Me!=Box&&You!=Box) {
                  //Collision = Tools.Collision((int)(CurrentX-(Width/2)), (int)(CurrentY-(Width/2)), Width, Width, Box.GetX(), Box.GetY(), Box.GetWidth(), Box.GetHeight(), 1);
                  boolean Col = Tools.BasicCollision((int)(CurrentX-(Width/2)), (int)(CurrentY-(Width/2)), Width, Width, Box.GetX(), Box.GetY(), Box.GetWidth(), Box.GetHeight());
               }
            }
         }
      }

      CurrentX-=DirectionX;
      CurrentY-=DirectionY;
   }
   return null;
}

If you have a headache the fundamentals are:

It figures out 10 points in between and detects whether it is inside, using BasicCollision:

public static boolean BasicCollision(int x, int y, int width, int height, int x2, int y2, int width2, int height2) {
   if(x<x2+width&&x+width>x2&&y<y2+height&&y+height>y2) {
      return true;
   } else {
      return false;
   }
}

My question is: Is there an easier way to detect this Line of Sight that doesn't severely impact my performance in large numbers? Any feedback?


texts: Accessing managers from game entities/components

texts:
I'm designing an entity-component engine in C# right now, and all components need to have access to the global event manager, which sends off inter-entity events (every entity also has a local event manager).

I'd like to be able to simply call functions like this:

GlobalEventManager.Publish("Foo", new EventData());
GlobalEventManager.Subscribe("Bar", OnBarEvent);

without having to do this:

class HealthComponent
{
    private EventManager globalEventManager;

    public HealthComponent(EventManager gEM)
    {
        globalEventManager = gEM;
    }
}

// later on...
EventManager globalEventManager = new EventManager();
Entity playerEntity = new Entity();
playerEntity.AddComponent(new HealthComponent(globalEventManager));

How can I accomplish this?


texts: 2D Game : How do I draw my entities (player, etc.) by their Y position?

texts:
I am using C# with MonoGame 3.6

A picture of what I mean: http://i.imgur.com/S3i5iB0.png You see, the little black box is drawn over the red box, because it is drawn before the red box gets drawn. Our view is diagonally forward, which means the red box should get drawn over the red one.

Now, I of course could loop through all entities and sort them by their Y coordinate, but I wanted to know if there was a faster way, as this would be totally inefficient if I had to do it on every game tick / every entity move.

Thank you!


texts:
I'm currently attempting to make a first person character using a rigid body.  I am aware that the character controller exists, but I believe my game will be very physics based so it's better if my character is a rigid body.  I currently can walk, and rotate the camera up and down with the mouse.  I am now trying to rotate my character left and right with the mouse, but this requires me to rotate my rigid body, not just the camera.  Here's my code so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] float walkSpeed = 3;
    [SerializeField] float cameraSpeed = 3;

    Vector3 direction;
    float cameraX;

    Rigidbody myRigidBody;
    [SerializeField] Camera myCamera;
    // Start is called before the first frame update
    void Start()
    {
        myRigidBody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        cameraX = -Input.GetAxis("Mouse Y") * cameraSpeed;

        myCamera.transform.Rotate(new Vector3(cameraX, 0, 0));
    }
    void FixedUpdate()
    {
        myRigidBody.AddRelativeForce(direction * walkSpeed, ForceMode.Acceleration);
    }

I believe that the rigid body function I should use to rotate left and right is MoveRotation (I'm still new to rigid bodies), but I'm open to ideas.  MoveRotation uses Quaternions, and I have no idea how to translate my mouse axis into a quaternion.
Here's my question, How do i implement the Y rotation for my rigid body first person controller?  Should I use torque, or somehow directly alter my rotation without using forces? Also, How do i translate the Mouse Axis into something I can use to rotate something?  thnx.
Edit:
I tried adding this line of code:
myRigidBody.MoveRotation(Quaternion.Euler(0, mouseX * cameraSpeed, 0));

for some reason it has no effect on my character at all, but I feel Like it's on the right track.  Why isn't this working?
Edit 2:
I added this line in Update:
rotateDirection = new Vector3(0, Input.GetAxis("Mouse X"), 0);

And this line in FixedUpdate:
myRigidBody.MoveRotation(Quaternion.Euler(rotateDirection));

Now when I move my mouse (I commented out my camera up and down movement to test) my character moves left and right for a tiny bit, but jitters back to it's original position, so It feels like I'm fighting it.  The rotation in the inspector jitters in the correct direction, negative if i move the mouse left, positive if right, but only for a very small amount, 1.45 being the most, and then reverts back to zero.  Also, it doesn't rotate smoothly, but jitters.  Anybody know whats going on?
Edit 3: changed it from addforce to addrelativeforce because that make it move forward based on local coordinates not global.


texts: How to address raycast failures due to tiny holes in a mesh?

texts:
Problem:

I have a racing circuit that is made out of tiles, each of which is made out of 2 triangles. I need to know over which tile my craft is hovering on; but since there are tiny holes between some of the tiles, casting a ray fails sometimes.

Note: fixing the mesh from within a 3D modeler is not an option.

Question:

Is there a robust method for approaching this problem ?


texts: Unity: Why do my 2 gameObjects 'share' materials?

texts:
no one has answered this on Unity answers yet so I thought I might as well ask this here:

recently, I imported my .blend game character and the character consisted of 2 colors: Red and black. Therefore as unity always does it creates 2 red and black materials for the colors of the character. Then, I imported the grass platform for my game. Because the grass platform is green and brown, Unity should have created 2 new green and brown materials and the platform should have stayed green and brown. But, instead, my grass platform decided to use my character's materials and my platform is now red and black. (If I import the grass platform first, my character becomes brown and green). Please help, this is an extremely annoying problem, thanks!


texts: Getting a sphere to roll down a .FBX object Unity3D/C#

texts:
I'm working on a little ramp and ball game in Unity, I modeled the ramp outside Unity and exported it to a .FBX file, then I imported the ramp in to Unity. I set up the ball and ramp, both have Rigidbodies, Ramp is set to isKinematic = true, yet when I play the game the ball just falls right through the ramp and hits the floor below it fine. So it's something wrong with the ramp.

Am I doing something wrong? Are .FBX files unable to apply physics?

Thanks,

Tim.


texts: given the position and velocity of an object how can I detect possible Collision?

texts:
I'm trying to detect Collision between autonomous moving objects and steer direction if collision is detected. so far I've been following a tutorial and I'm having a hard time to fully understand how it works especially the role of the dot product

foreach (GameObject t in targets) //get me all moving agents
{
 Vector3 relativePos;
 Agent targetAgent = t.GetComponent<Agent>(); //access properties like velocity
 relativePos = t.transform.position - transform.position;
 Vector3 relativeVel = targetAgent.velocity - agent.velocity;
 float relativeSpeed = relativeVel.magnitude;

//can someone explain this part of code how did we calculate the time of collision?

 float timeToCollision = Vector3.Dot(relativePos, relativeVel);
 timeToCollision /= relativeSpeed * relativeSpeed * -1;
 float distance = relativePos.magnitude;
 float minSeparation = distance - relativeSpeed *
 timeToCollision;


texts:
What I'm trying to do is set a bunch of points to create a shape and then fill everything in within those points. It needs to be done in 3D becasue this is being used as a way to generate a texture for another shader I'm working on so the other shader knows what to highlight and what to not highlight.

Right now what I have a camera setup and I have it drawing a simple square with line lists. Eventually this will be extended upon to be more than just a simple square.

What is the best way to go about filling this shape in with a color, keeping in mind that it won't be a square later on.


texts: Simple way to detect collision between two bitmaps on android surface view

texts:
I'm looking for a standard way to detect collision between two bitmaps inside a surface view. I tried the intersect method with two rectangles, but it doesn't log.

practiseA = new Rect(500, 500, 500, 500);
practiseB = new Rect(500, 500, 500, 500);

public void isIntersecting() {
    Log.d("yeah", "hello");
    if (practiseA.intersect(practiseB)) {
        Log.d("collision", "yes");
    }
}

So can someone tell me what I'm doing wrong or give me a different method?

I saw this complicated algorithm but didn't understand what to feed it:

sqrt( ( ax - bx ) ^ 2 + ( ay - by) ^ 2) <= aR + bR

What's aR and bR?


texts: adding vertical scrolling to 2D platformer in libgdx

texts:
I am trying to make a two sided platform game in Libgdx. Where I am scrolling through the TiledMap.
I was easily implementing the horizontal scrolling using..

camera.position.x = player.getPositionX();

and it works fine. But when it comes to Vertical scroll .. I am observing very bad effects doing the same thing on y-axis. I tried it many ways. But No code could give could a real look and feel.
Later I happen to find this video

http://blog.mimeoverse.com/post/581467761/the-ideal-platformer-camera-should-minimize

it says "
The ideal platformer camera should:

minimize vertical motion
lead in the direction the player is facing
remain motionless during horizontal micro-adjustments
The secret to achieving all three is (what I call) the trap. The trap is an invisible rectangle (made visible for this demo), roughly twice as wide and tall as the player sprite, with the same starting coordinates. Rather than follow the player sprite directly the camera follows the trap. When the player moves within the trap, the camera does not move. The trap only moves when the player pushes against one of its edges.
"
it demonstrates a good idea but Still there still seems something bad .. I am writing some wrong code

Rectangle trap_old,trap_new;

.....

trap_old = new Rectangle(player.getPositionX()-2*player.getWidth(),
                        player.getPositionY()+5*player.getHeight(),
                        5*player.getWidth(),
                        6*player.getHeight());

//.. inside render

trap_new = getNewTrapArea(player.getPositionX(),
                        player.getPositionY(),
                        player.getWidth(),
                        player.getHeight());

camera.position.x = trap_new.x;
camera.position.y = trap_new.y;
camera.update();

private Rectangle getNewTrapArea(float positionX, float positionY, float width, float height) {
    Rectangle temp = new Rectangle(positionX, positionY, width, height);
    if(temp.overlaps(trap_old))
        trap_new = trap_old;
    else
        trap_old = trap_new = new Rectangle(positionX-2*width, positionY+5*height, 5*width, 6*height);
    return trap_new;
}


texts:
Let's take some old popular at a time but abandoned game: WorldRacing/HiOctane/Constructor/any other. Say I with a team want to revitalize said game and bring it to year 2011 without major changes and then work on improving it (e.g. add multiplayer). Also it is important to keep the game's spirit, assets, story, music, so basically the game remains the same, but gets better (e.g. adapting DOS game to Win7).

My questions are from "How is it usually made?" area:

How do I purchase rights to the title and the game's assets (graphics, sounds, music, storyline). Whom to contact and what purchase options are possible? Is it possible to obtain source codes, design documents.
How to deal with various platforms, is it terms of contract saying which platforms are allowed to be used if there are several?
How to deal with localizations in other languages, are they to obtain from other companies or do they belong to master publisher?
What could be the reasonable price for said games in example?
Is it possible to pursue owners to release the game as open source?

Remember Heroes of Might and Magic was owned by New World Computing, but later changed its owner to Nival. I'm interested in that sort of process.


texts: A way to store potentially infinite 2D map data?

texts:
I have a 2D platformer that currently can handle chunks with 100 by 100 tiles, with the chunk coordinates are stored as longs, so this is the only limit of maps (maxlong*maxlong).
All entity positions etc etc are chunk relevant and so there is no limit there.

The problem I'm having is how to store and access these chunks without having thousands of files. Any ideas for a preferably quick & low HD cost archive format that doesn't need to open everything at once?


texts: How can I simulate a "Hot Swap" betwen Audio Clips?

texts:
I have a Unity project with 3 separate looping Audio Clips and a single Audio Source. Based on certain events, I swap between which of them are playing.

This works fine, but whenever I swap between Audio Clips, the AudioSource stops playing, and must be restarted... which means it starts over from the beginning.

As the Audio Clips are the same length, how should I handle the logic to pickup where the previous Clip last left off? Neither Unity's AudioClip nor AudioSource classes seem to have either a "PlayFromTime()" or "GetPercentPlayed()" method that would facilitate using a single Audio Source.

What's the expected way to handle such a scenario? Simultaneously "play" from 3 AudioSources at once, muting 2 of them and leaving the last the only one that is actually heard?


texts:
I get inconsistent results when I run this code as standalone Windows on Mono and IL2CPP backends.

var a = new Vector3(-1.26998901f, 0, -0.849998474f);
var b = new Vector3(20.0799999f, -1, 164.580002f);
var dot = Vector3.Dot(a, b);
var mydot = (float) ((double) a.x * (double) b.x + (double) a.y * (double) b.y + (double) a.z * (double) b.z);

+-------+----------------+-------------+
|       | Mono or Editor |   IL2CPP    |
+-------+----------------+-------------+
| dot   | -165.394135    | -165.394119 |
| mydot | -165.394135    | -165.394135 |
+-------+----------------+-------------+

Take a look at the dot result on IL2CPP backend in the table above.

My mydot implementation should be equivalent to Vector3.Dot(Vector3, Vector3) according to dotPeek in Rider.

Decompiled Vector3.Dot(Vector3, Vector3)

/// <summary>
///   <para>Dot Product of two vectors.</para>
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
public static float Dot(Vector3 lhs, Vector3 rhs)
{
  return (float) ((double) lhs.x * (double) rhs.x + (double) lhs.y * (double) rhs.y + (double) lhs.z * (double) rhs.z);
}

Unity version: 2018.4.12f1

What causes Vector3.Dot(Vector3, Vector3) to give a different result on IL2CPP?


texts:
I'm thinking about programming a 2d simulation of a spaceship that takes damage depending on where the projectile came from (e.g. from behind - engine, from the front - lasers, sides - hull, etc.). When a given part is below a certain durability factor it explodes into physics simulated particles. What is a good way of storing such particles (ship built out of parts, parts built out of particles, e.g. 6px triangles) taking into consideration the following:

different parts have different shapes,
it might be needed to add more parts in the future,
possibility of avoiding a pixel-perfect projectile-to-part collision detection,
the spaceship should be affected by physics but particles shouldn't unless exploding.


texts: NavMeshAgent in Unity giving jerky performance

texts:
I am using NavMeshAgent in my Unity project to calculate and move my object to a particular location.

When I do:

navMeshAgent.destination = destinationPt

the object starts moving, but the motion of the object is very jerky.

Is there a way to override the function which is responsible for the jerkiness of the object motion? Or is there a way I can remove the jerkiness of the motion some other way?

I also tried setting

navMeshAgent.updatePosition = false

after which I use

navMeshAgent.CalculatePath(destinationPt, path)

to get the path, but then after this I am not able to figure out how to write my own logic to make the object move. I want a smooth motion with a given acceleration and a max velocity.


texts:
Are there any shoot-em-ups in which the enemies actually evolve as a response to their relative success against the player?

By evolve, I mean that each enemy has some genetic information encoding their behaviour. Enemies which last longer or do more damage are allowed to mix their genes to create new enemies. This way the enemies would become better adapted to the particular player.


texts: Fair combat system for new players on RTS game

texts:
I'm working on an idea/concept for a multiplayer game that I want to develop after my functional analysis but I'm still thinking of a way to implement a proper, fair combat system between new and existing players.

A player can create a new village/town once, anywhere on a map (this is key!). There is an attacking period where players can attack each other but I want to limit the possibility that more progressed players can attack beginners and prevent them from growing. Tribal Wars for example does this by creating new villages further away from the more progressed players. In my case, a user can create his town anywhere on the map, so I'm looking for a fair solution for all players.

A few examples of combat systems used in other games that I thought off:

RuneScape

  Any player within a particular level range of your combat level can be
  attacked in the Wilderness. The range is calculated by taking your
  current combat level and adding or subtracting the current Wilderness
  level you are in.

Tribal Wars

  Every new player is assigned a new village at the border from the
  previous players. So older, longer players are in the center while new
  players are further away from them, repeatedly. Combat system is based
  on the distance between 2 villages, so if older players want to attack
  a new player, it would take significantly more time to attack those
  players for less rewards.


texts: Why is my inherited class's transform always null?

texts:
I have a class inherited to another class, and I can't get the transform on the inherited class.

Here's what i have and trying to do

Class A:Monobehavior{}

Class B:A{}

//somewhere else

A object = new B();

but right now, whenever I try to get the transform of object, either from a function in B or out here via object.transform, it will always return null.

How do I fix this?


texts: Is it legal to clone a character from other game?

texts:
Is it legal to make a character very similar/exact from other game? E.g. take characters from Team Fortress 2 game, remake them in pixel art and use it in my game, but just change their names(with an intent to make money).

Would I get in trouble?


texts:
Do you know any gamedev related magazines ?
I only know http://www.gdmag.com/ and http://www.gamasutra.com/ .

I also know http://ffdmag.com/ ,there's texts about flash (sometimes related to games)


texts: Label not properly centered in TextButton

texts:
I'm using LibGDX v1.1.0 and I see that the label of a TextButton is not properly centered. I have the following code:

m_resumeButton = new TextButton("resume", skin);
m_resumeButton.addListener(new ChangeListener() {
    public void changed(ChangeEvent event, Actor actor) {
        m_state = GameState.RUNNING;
        getGame().getWorld().pauseWorld(false);
    }
});

The default TextButtonStyle is defined as:

"com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle": {
    "default": {
        "up": "menu-button",
        "down": "menu-button-down",
        "checked": "menu-button-down",
        "disabled": "menu-button-disabled",
        "font": "font24",
        "fontColor": "white"
    }
}

The menu button images are simple 240x48 bitmaps saved as 9-patch images. An image can be found here to illustrate the problem:

https://www.dropbox.com/s/cwuhu5xb9ro5w6m/screenshot001.jpg

Am I doing something wrong? Or is there a problem with the button images I'm using?


texts:
Accoring to this, depth testing is usually performed after the fragment shader stage. Why is that? I thought that a fragment is sent with its depth value to the FS, then the depth test happens before the FS executes, so the gpu can avoid a spare FS execution if the pixel is covered by a closer one.

Why is it not like that?


texts: How to make a homing projectile make a more objective path to the target?

texts:
I'm having trouble trying to get a projectile thrown by a tower to hit the player quickly.

See the image below:

The projectile hits the ground very close to where the player was.

If the player did not move so much, the projectile would certainly hit him, but even by slowing the player down and increasing the speed of the shot, the projectile often does not hit the player.

What happens almost always is the projectile orbiting the player.

If the player stands still when the tower starts firing, the projectile hits him, the problem happens when the player moves, the projectile does not follow the player correctly.

Expected result:

I have already tried to modify the speed of the player and the projectile, but I have not obtained efficient improvements in the result. I tried to modify the gravity (of the projectile and its mesh), friction. All to no avail.

Projectile BP:

EDIT 1

With this code I was able to stop the projectile from crossing the floor:

But the projectile still orbits the player:

If the player does not stop moving, the projectile orbits it indefinitely.

Below is how the components went after I turned off the physics at all.

Sphere Collision:

Static Mesh:

ProjectileMovement:


texts: How to create a boxcollider, which surrounds the gameobject and all of his children?

texts:
I have a Car, who needs a Box Collider.
If the car would be 1 single mesh, i would only need to call:

        boxCol = gameObject.AddComponent<BoxCollider>();

and it would create a boxCollider, which fits perfectly my car, based on my car's mesh.

Now I have a car which exists of many different parts in the hierarchy. (for example: Body of the car is the parent of the 4 doors. Every door is 1 seperate gameobject, and has a doorknob child etc. )

now i need a script which changes the boxCollider so, that it has the box surrounding the whole car.

i found:
http://answers.unity3d.com/questions/22019/auto-sizing-primitive-collider-based-on-child-mesh.html

but it just doesnt get me the right collider.

Edit:
I just tried again - and the Boxcollider stays the same.

using UnityEngine;
using UnityEditor;
using System.Collections;

public class ColliderToFit : MonoBehaviour
{

    [MenuItem("My Tools/Collider/Fit to Children")]
    static void FitToChildren()
    {
        foreach (GameObject rootGameObject in Selection.gameObjects)
        {
            if (!(rootGameObject.GetComponent<Collider>()  is BoxCollider))
                continue;

            bool hasBounds = false;
            Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);

            for (int i = 0; i < rootGameObject.transform.childCount; ++i)
            {
                Renderer childRenderer = rootGameObject.transform.GetChild(i).GetComponent<Renderer>();
                if (childRenderer != null)
                {
                    if (hasBounds)
                    {
                        bounds.Encapsulate(childRenderer.bounds);
                    }
                    else
                    {
                        bounds = childRenderer.bounds;
                        hasBounds = true;
                    }
                }
            }

            BoxCollider collider = (BoxCollider)rootGameObject.GetComponent<Collider>();
            collider.center = bounds.center - rootGameObject.transform.position;
            collider.size = bounds.size;
        }
    }

}


texts:
I've got a very annoying problem that I have been stuck on for a few days and I can't figure it out.

It is for a wall jump.

I basically want my wall jump to have a bit of force away from to wall to make it look and feel better than just jumping up straight.

The problem is, when i add a force on the x axis, it does not register when i am also holding the arrow towards the wall. If I am not holding down the walking button, then press jump...then the x force works.

I have a feeling that the horizontal axis force is competing with the opposite force that i want to add to the player when he hits the jump button...

Walking code:

private void ApplyMovement()
{
    if (isGrounded)
    {
        myRigidbody.velocity = new Vector2(movementSpeed * movementInputDirection, myRigidbody.velocity.y);
    }
    else if (!isGrounded && !isWallSliding && movementInputDirection != 0)
    {
        Vector2 forceToAdd = new Vector2(movementForceInAir *  movementInputDirection, 0);
        myRigidbody.AddForce(forceToAdd);

        if (Mathf.Abs(myRigidbody.velocity.x) > movementSpeed)
        {
            myRigidbody.velocity = new Vector2(movementSpeed *  movementInputDirection, myRigidbody.velocity.y);
        }
    }
    else if (!isGrounded && !isWallSliding && movementInputDirection == 0)
    {
        myRigidbody.velocity = new Vector2(myRigidbody.velocity.x * airDragMultiplier, myRigidbody.velocity.y);
    }

    if (isWallSliding)
    {
        if (myRigidbody.velocity.y < -wallSlideSpeed)
        {
            myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, -wallSlideSpeed);
        }
    }
}

Jump code:

private void Jump()
{
    if (canJump && !isWallSliding)
    {
        myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
        numberOfJumpsLeft--;
    }
    else if ((isWallSliding || isTouchingWall) && !isGrounded && canJump)
    {
        isWallSliding = false;
        numberOfJumpsLeft--;
        Vector2 forceToAdd = new Vector2(wallPushForce * -facingDirection, wallJumpForce *
                                         wallJumpDirection.y);
        myRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse);
    }
}

Where I call The code:

void Update()
{
    CheckInput();
}

private void FixedUpdate()
{
    ApplyMovement();
}

private void CheckInput()
{
    movementInputDirection = CrossPlatformInputManager.GetAxisRaw("Horizontal");

    if (Input.GetButtonDown("Jump"))
    {
        Jump();
    }

    if (Input.GetButtonUp("Jump"))
    {
        myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, myRigidbody.velocity.y * variableJumpHeightMultiplier);
    }
}

Any help would be much appreciated.

Thanks in advance


texts: When do you use StartCoroutine and when Invoke?

texts:
I am confused. Both seem to do the same thing: Delay a method.

Both Invoke and StartCoroutine allow you to call a method by name (string).

StartCoroutine("functioncalls", 2f);
StartCoroutine(functioncalls());

Invoke:

void Call()
{
    Invoke("FunctionCall",2f);
}

void FunctionCall()
{
    Debug.Log("this function run");
}

StartCoroutine:

void Call()
{
      StartCoroutine(functioncalls());
}

IEnumerator functioncalls()
{
    yield return new WaitForSeconds(2f);
    Debug.Log("this function run");
}

Both do the same thing, or not?

What exactly is the difference between Invoke and StartCouroutine? In which situation would I use one and when the other?


texts: Database works on unity editor,but not on android device

texts:
I am working on database connectivity in unity.When I run my project I am able to access my database(retrieving and inserting data into database).But the problem is that when I take the android out the project I am having not able to accessing my database on my mobile android device. It seems that it doesn't read my database or I don't know my database is not included upon build.

Below code is working fine.
I am using MySQL

string loginCode="http://localhost/unity_db/login.php";
string registerCode="http://localhost/unity_db/register.php";

public string username="";
public string password="";
public string output="";

void Start () {
    Debug.Log("print");
}
// Update is called once per frame
void Update () {
}

void OnGUI()
{
    GUI.Window (0, new Rect (Screen.width/4,Screen.height/4,Screen.width/2,Screen.height/2-5), LoginWindow, "Login");

}
void LoginWindow(int windowID)
{
    GUI.Label (new Rect (140, 40, 130, 100), "Enter the Username");
    username = GUI.TextField (new Rect (25, 60, 375, 30), username);
    GUI.Label (new Rect (140, 92, 130, 100), "Enter the Password");
    password = GUI.TextField(new Rect (25, 115, 375, 30), password);
    if (GUI.Button (new Rect (29, 160, 175, 50), "Login"))
    StartCoroutine(handleLogin(username,password));
    GUI.Label (new Rect (55, 222, 250, 100),output);
    if(GUI.Button (new Rect (225, 160, 175, 50), "Register"))
    StartCoroutine(handleRegister(username,password));
}

IEnumerator  handleLogin(string user,string pass)
{
    /*if (username == "Achu" && password == "achu123") {
                    Debug.Log (username + password);
            } else {
        Debug.Log ("error");
            }*/

    string login_url = loginCode + "?username=" + user + "&password=" + pass;
    WWW logindata = new WWW (login_url);
    yield return logindata;
    if (logindata.text == "right") {
        output="login successful";

    } else {
        output="invalid user pass";
    }

}
IEnumerator  handleRegister(string user,string pass)
{

    string register_url = registerCode + "?username=" + user + "&password=" + pass;
    WWW registerdata = new WWW (register_url);
    yield return registerdata;
        if(registerdata.text=="registered")
        {
        output="registration successful";
        }
        else{
            output="registration failed pass";
        }

    }

}


texts: How to set multiple times, in a single spritebatch, the same pixel shader parameter

texts:
I make a test with Effect class in XNA and I want to set multiple times the same parameters (MyParameter in below code).

My code is :

[...]
//In Engine class
Effect ShaderEffect = GameEngine.Instance.Content.Load<Effect>(@"shaders\test");

spriteBatch.Begin(
    SpriteSortMode.Deferred,
    BlendState.AlphaBlend,
    SamplerState.PointWrap,
    DepthStencilState.Default,
    RasterizerState.CullNone,
    ShaderEffect);

[...]

//in drawable class
foreach(//big loop) {
     ShaderEffect.Parameters["MyParameter"].SetValue(//random vector4);
     spriteBatch.Draw(
            SpriteSheet,
            ScreenRect,
            sprite_to_draw.Rectangle,
            color,
            rotation,
            Scene.getInstance().Camera.Position,
            sprite_to_draw.SpriteEffect,
            layer
     );
}

[...]

//In Engine class
spriteBatch.End();
[...]

But on my screen it look like the Parameter "MyParameter" is not overwrite.

So can I overwrite it and If yes do you know how ?

Thanks


texts: .NET Framework version is fixed for Unity scripts?

texts:
It seems that the C# project that Unity creates uses version 4.7.1. But I want to use only the latest version and do not want to install lots of older versions of .NET Framework targetting packs that I do not use. Even if I change the version to 4.8 and save the project, if I add a new script asset, then the version changes back to 4.7.1.

So, my question is, do I have to use the version that Unity sets by default? Or is there a way to make Unity always use the latest .NET version such as 4.8, in this case? If the answer is the former, I will give up and install 4.7.1.


texts: Timing Calculations for Opengl ES 2.0 draw calls

texts:
I am drawing a cube in OpenGL ES 2.0 in Linux.
I am calculating the time taken for each frame  using below function

#define NANO 1000000000

#define NANO_TO_MICRO(x) ((x)/1000)

uint64_t getTick()
{
  struct timespec stCT;
  clock_gettime(CLOCK_MONOTONIC, &stCT);
  uint64_t iCurrTimeNano = (1000000000 * stCT.tv_sec + stCT.tv_nsec); // in Nano Secs
  uint64_t iCurrTimeMicro = NANO_TO_MICRO(iCurrTimeNano); // in Micro Secs

  return iCurrTimeMicro;
}

I am running my code for 100 frames with simple x-axis rotation.
I am getting around 200 to 220 microsecs per frame.

that means am i getting around (1/220microsec = 4545) FPS
Is my GPU is that fast?
I strongly doubt this result.

what went wrong in the code?


texts: How the game engine handles camera view in DirectX

texts:
I am quite confused with how the game engine handles camera view in DirectX. I know all the matrix stuffs, but where the projection matrix goes finally seems rarely mentioned.
I looked up in the sample project by microsoft https://msdn.microsoft.com/en-us/windows/uwp/gaming/tutorial--create-your-first-metro-style-directx-game
in the GameRenderer::CreateWindowSizeDependentResources() method, the projection process is implemented
XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D();

        ConstantBufferChangeOnResize changesOnResize;
        XMStoreFloat4x4(
            &changesOnResize.projection,
            XMMatrixMultiply(
                XMMatrixTranspose(m_game->GameCamera()->Projection()),
                XMMatrixTranspose(XMLoadFloat4x4(&orientation))
                )
            );

        d3dContext->UpdateSubresource(
            m_constantBufferChangeOnResize.Get(),
            0,
            nullptr,
            &changesOnResize,
            0,
            0
            );

However I can't figure out what the UpdateSubresources method has anything to do with projection (yet such projection in the UpdateSubresources method exists in some other samples I found). But wouldn't it be absurd to change the entire buffer every frame for projection? Isn't the data in the buffer in world view coordinates?
The vertex shader seems also take the task of projection
PixelShaderInput output = (PixelShaderInput)0;

    output.position = mul(mul(mul(input.position, world), view), projection);

I do think this one is more plausible for the task.
So the questions are:

Which one exactly is the process of projection, and how does it come along in two places?

If it happens in UpdateSubresources, what should I do with dynamic buffer?

If it happens in the shader, where does the world, view, projection matrics come from?

How should I use it with SharpDX


texts: How do I correctly make character sprite direction match player inputs?

texts:
In my top down game I can move the character around and the character will even face the direction he is moving.

However, there is some weird behavior I'm having: when you hold down one direction and then another direction the graphic updates to that direction, but if you keep holding the direction prior it does not update to the correct graphic.

Here is my function that handles the rendering of the player graphic. When that happens it looks like the character is walking sideways. I haven't added animation yet. It just tries to have the right graphic with the corresponding direction.

render: function() {
      var game = roguelike.game;
      var map = roguelike.map;
      var image = game.library.images[1];
      var ctx = game.library.ctx;
      var centerX = game.library.canvas.width / 2 - map.tileSize / 2;
      var centerY = game.library.canvas.height / 2 - map.tileSize / 2;
      switch(this.facing) {
        case "left":
          var cropX = 1 * map.tileSize;
          var cropY = 5 * map.tileSize;
          break;
        case "up":
          var cropX = 1 * map.tileSize;
          var cropY = 7 * map.tileSize;
          break;
        case "right":
          var cropX = 1 * map.tileSize;
          var cropY = 6 * map.tileSize;
          break;
        case "down":
          var cropX = 1 * map.tileSize;
          var cropY = 4 * map.tileSize;
          break;
      }
      ctx.drawImage(
        image,
        cropX,
        cropY,
        map.tileSize,
        map.tileSize,
        centerX,
        centerY,
        map.tileSize,
        map.tileSize
      );
    }

Also you might want to see how I handle my player.facing state. I do it this way.

window.onkeydown = function (event) {
  var player = roguelike.player;
  switch (event.keyCode) {
   //Left
   case 37:
    player.facing = "left";
    player.moving.left = true;
    break;
   //Up
   case 38:
    player.facing = "up";
     player.moving.up = true;
     break;
   //Right
   case 39:
    player.facing = "right";
    player.moving.right = true;
    break;
   //Down
   case 40:
    player.facing = "down";
    player.moving.down = true;
    break;
 }
};


texts: Why is my character not moving when applying an acceleration to it?

texts:
I'm having issues with my character in terms of gravity and the character bouncing up and down. You can find more information about it in the link below.

Character bouncing off ground due to gravity

I thought the answer below fixed it unfortunately it didn't after doing some more digging through the original platformer example on the app hub.

Platformer Starter Kit

The bouncing issue was resloved in the following way in the original.

The velocity would be added to the position

position += velocity;

Then the position would values would be even out.

position = new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y));

The x movement is below

accerlation = 0.046875f

velocity.X = velocity.X + accerlation;

and gravity is being added like so

private float gravity = 0.21875f;

velocity.Y = velocity.Y + gravity;

The issue is that the values are so small that once they've been added they are taken off again resulting in the character not moving. What is the best approach to solving this issue ?


texts:
When playing a Video in my OpenGL Game (e.g. startup video), I want to sync it with my delta time. What is the delta time and how to use here.

Do I need to sync with the delta time (and how?) or is there another way to sync my video? I'm using my own video file reader.


texts: Blender model doesn't show up in monogame

texts:
I have a problem getting blender models to show in monogame on windows. Using latest monogame 3.4, fresh blender 2.76b, developing in Visual Studio 2010 using OpenGL Monogame template.

What I'm trying to do is to create a simple model in blender - a sphere, export it as FBX, getting it properly into Monogame Pipeline - here it compiles fine. But then it's invisible in the application. I load it this way:

model = Content.Load<Model>("MyBall");

I draw it this way:

model.Draw(Matrix.Identity, camera.View, camera.Projection);

Also tried other drawing method with enumerating meshes.

The code seems to work in general, because I can see a model which I downloaded from Internet. However I got one or two working, with tens of other downloaded models which don't work and tens which the Pipeline tool will not accept.

I can move around in my app to make sure I' m not inside a model. Also tried adding material in Blender but with no luck. But I'm still learning Blender.

Also tried Autodesk FBX converter, but didn't help anything.

Where's the catch?


texts:
I have a basic 2D particle system  and I'm now looking to implement collisions, however I'm not sure on what the best way to do it is. My game is tile based and runs in XNA Game Studio 4.0. I've seen the platformer sample which has the player's collisions system working like this:

for(int x = leftTile; x <= rightTile; x++)
{
    for(int y = topTile; y <= bottomTile; y++)
    {
        if(TileIsSolid(x, y))
        {
            //Resolve...
        }
    }
}

But I don't know if this is feasible to run on 300 particles at one time, and it needs it support tiny fast moving objects such as bullets from a weapon. So how do I go about implementing 2D tile based particle collisions?


texts: Are there any frameworks that allow me to write games in C# on Linux?

texts:
I'm looking for something like an alternative to XNA - I don't care whether it's a 2D or 3D engine. It's not because I dislike Windows or am anti-Microsoft; it's because I like running Linux, code in Linux completely (for C# I use Mono, obviously), and by no means have any hardware to actually support programming in XNA, simply because my video card is 6 years old. I also don't have a Windows 7/Vista CD for DirectX 10.

Thus, for game development I'm kind of stuck in the stone age. Yet, I like C# very much and would hate to have to drop it as a language due to this.

Is there anything I can do?


texts: Dot based light mask with shader on sprites

texts:
So I have a scene, completely based on 2D sprites. I want to render "light sources" into a seperate frame buffer (so mostly dots around, for example, the centre of a flame) and then render that frame buffer with my "lighting" shader above my whole scene, causing the light sources to "tint" the surrounding pixels, mostly by blending a pixel with the light source's color dependant on it's distance to the nearest light source.

The question:
What concepts should I apply here to get the results I want?
What am I doing wrong right now?

I have here a few concept drawings:

The scene without lighting:

The framebuffer of the scene containing the light source (the top yellow pixel of the flame):

The result of rendering the framebuffer as a texture with the glow shader. I also "simulated" a 2nd buffer with a smaller radius and a yellow light at the same position.

Alternatively, and closer to my first approach to the idea, imagine the whole framebuffer of the 2nd pixel transparent but the dot at the center.

What I wasn't able to mock up quickly was a gradient of the lighting, dimming it at the edges and having it brighter at the center.

The current idea needs to conform this fragment shader's layout:

#version 400
uniform sampler2D color_map;
layout(std140) uniform Sprite {
    vec2 position;
    vec2 size;
    vec2 position_in_texture;
    vec2 size_in_texture;
    float rotation;
};
in vec2 texture_coordinate;
layout(std140) uniform Color {
    vec4 color;
};
layout(location = 0) out vec4 out_color;
void main(){
    vec4 tex_color = texture2D(color_map, texture_coordinate);
    vec2 diff;
    vec2 norm;
    vec2 sample_coordinate;
    out_color = tex_color;
    int radius = 4;
    int count = 1;
    norm = vec2(radius/size.x, radius/size.y);
    for(int i=-radius; i < radius; i++){ //Sample each pixel around the one rendered right now and add it's color to the current one with a certain gradient factor
        for(int j=-radius; j < radius; j++){
            diff = vec2(i/size.x, j/size.y);
            sample_coordinate = texture_coordinate + diff;
            if(0.0 <= sample_coordinate.x && sample_coordinate.x <= 1.0 && 0.0 <= sample_coordinate.y && sample_coordinate.y <= 1.0){
                tex_color = texture2D(color_map, sample_coordinate);
                if(tex_color != vec4(0.0,0.0,0.0,0.0) && sample_coordinate != texture_coordinate && length(diff) <= length(norm)){
                    out_color = (out_color * count + tex_color * (1.0 - (length(diff) / length(norm)))) / (count+1);
                    count++;
                }
            }
        }
    }
}

I am planning on making the radius variable by passing it as another uniform element.
With what I am doing there, I don't get the results I am looking for.

Though through experimenting I got this glow-shader, which I like, but the edges of the logo are still a bit too dark though (left the passed frame above the original, that is right):


texts: Gizmos.DrawMesh does not render anything

texts:
I would like to draw a procedural mesh as a gizmo:

Gizmos.DrawMesh(mesh);

however this does not render anything no matter what. I can confirm that the mesh in question is a correct one by both GetComponent<MeshFilter>().mesh = mesh assigning it to Renderer and rendering it using default material and Gizmo.DrawLine drawing it edge-by-edge.
No error are logged in debug window, setting position or flipping triangle orientation has no effect neither. Version of Unity is 5.6.2f1. Am I missing something?

void Start ()
{
   GetComponent<MeshFilter>().mesh = mesh; //renders without any problems
}

void OnDrawGizmos()
{
   Gizmos.color = Color.red;
   Gizmos.DrawMesh(mesh);//nothing rendered
   //renders without any problems
   for (int i = 0; i < mesh.triangles.Length / 3; i++)
   {
      Gizmos.DrawLine(mesh.vertices[mesh.triangles[i * 3 + 2]], mesh.vertices[mesh.triangles[i * 3]]);
      Gizmos.DrawLine(mesh.vertices[mesh.triangles[i * 3]], mesh.vertices[mesh.triangles[i * 3 + 1]]);
      Gizmos.DrawLine(mesh.vertices[mesh.triangles[i * 3 + 1]], mesh.vertices[mesh.triangles[i * 3 + 2]]);
   }
}


texts: I wanted to pick up Monogame, but I can't find documentation. All I see on GitHub is some tutorials. I'm looking for class reference like this from XNA.


texts: In games like Minecraft the textures such as grass when lined up side-by-side it looks like one big perfect texture. When I make a texture it's never even and you can see the different blocks. How do the textures kinda tessellate with each other?


texts: 90% CPU on Profile Editor: Throttle mainMessageLoop

texts:
I have a big problem in my Unity game, in almost every scène of my game, my editor is laggy, when I record Porfile Editor / deep profile editor, here is the result:

I have no idea what is this throttle MainMessageLoop, what can I do ?
Thanks you !


texts: How can you detect object/s using raycast from mouse cursor?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    void Start()
    {

    }

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1000))
            if (hit.transform.tag == "Interactable")
            {
                print("I'm looking at " + hit.transform.name);
            }
            else
                print("I'm looking at nothing!");
    }
}

This is working fine but this send raycast hit from the camera. I want to send the raycast from the mouse cursor so if the mouse cursor is moving over object it will detect it. Just instead the camera the mouse cursor.


texts: Help with building a platformer engine on top of cocos2d

texts:
I am a C# programmer making a transition to game programming and hence C++. I want to make a reusable platformer engine (for now I want to start small) on top of cocos2d/box2d to make prototyping of new ideas easier.

My idea is nothing new, I want to use a component model to be able to build game objects by various blueprints. My biggest problem is the implementation of my idea as my c++ skills aren't great.

The idea is that every game object is a composition of raw data and behavior/actions where raw data is expressed as set of components eg. "VisualComponent", "PhysicsComponent" etc.. and actions defines the "mind" of the object or what it can do: "Move","Jump","Roll","Hide" etc..

Below you can see I made simple actions/states diagram, the actions has a flow. some actions are blocking other actions while their in progress. This is the notion I want to have with this engine. A set of actions or behaviors that plays nicely together. actions should be stacked if possible so shooting while moving/jumping is allowed. But shooting while rolling isn't allowed hence rolling is a blocking action. (I'm not talking about reactions yet but it is too a concern).

Ok, so back to the GameObject here is what I want to achieve.

GameObject should have plug-able components mechanism to be built by it's blueprint (Some sort of data structure maybe JSON).
Needs to have set of defined actions/behaviors.
Most important: If the object isn't a dummy (has a brain) it needs a composer that actually makes sense of what to do next, and that's a huge subject on where the logic of all the stuff should happen.

Here I made another simple diagram of how I see the object interactions with the world (it can get the actions by the AI or user input)

here is a theoretical example of what I want to be able to do (pseudo):
it's me talking to the engine if it was a human.

create a new object
add a physical component: circle body and radius size of 5
add a visual component: idle sprite "idle.png", jump animation "jump.gif" (needs to follow the physics object at all times)
add userControlComponent:(needs to communicate to physics component of the relevant physics actions)

bindkey('d', moveAction(force))
bindkey('a',moveAction(force))
bindkey('space',jumpAction(force))
(the actions change/replace states and block other states)

Hardest part for me to think about is how to keep actions intact with the specific components they affect. And how to add more logic without making this model a monstrous thing. Let's say I have jump now I want to be able to give my character double jump it's hard for me to visualize how it can be done without serious changes each time that can mess with the flow" of actions/states. Furthermore it's really hard for me to think about reactions logic cause that's not even controlled by the object itself.

I will be happy to hear your thoughts and ideas of this model. If it's outdated or totally crap I'd like to here it too. Mostly I'd like to hear about how you would implement such system.


texts: How to set keys for emission on/off for a prefab?

texts:
I am making a prototype for a Mario game and am having difficulty completing a canned animation for a prefab. There is an item box asset that has 3 materials and an "ItemGet" animation. One of these materials has an active emission property that is supposed to turn off during a specific frame of the "ItemGet" animation. These boxes will have an "Active" and "Inactive" state.

While "Active", the item box just bobs up and down and IF Mario hits the trigger, the "ItemGet" animation plays (and the player gets a unique item). The box then becomes "Inactive".
While "Inactive", no animations play, the emission effect is gone and the trigger cannot be reactivated.

Challenges:

finding the correct property to set a keyframe for in the Animations panel.
Making sure Active versions of the prefab remain Active after any ItemBox becomes Inactive and that all materials don't change when GetItem plays.

Ideas:

Instead of keying the emission on/off property (assuming that exists and does what I think it does; trouble finding it), swap the materials.
( . . . ), swap the mesh.

Can somebody please help me find a viable way to finish this animation that fits this object's intended use-case?


texts: How can I remove scores or ban users from Google Play leaderboards?

texts:
I have included Google Play game services in my Android game. I see lot of users posting fake scores.

Can I ban them or can I delete these scores somehow?


texts: Physics for movement in a topdown 2d game?

texts:
I'm implementing player movement for a simple topdown game, how would I handle more "advanced" concepts in physics to make my player movement feel more natural?
Right now I have something like this:

void update(double delta) {
    dx = dy = 0;

    if (left) {
        dx -= 1;
    }
    if (right) {
        dx += 1;
    }
    if (up) {
        dy -= 1;
    }
    if (down) {
        dy += 1;
    }

    if (dx != 0 || dy != 0) {
        x += dx * delta;
        y += dy * delta;
    }
}

How would I go about implementing things like friction, acceleration, drag, and so on?


texts:
I've never tried blur until recently, and by that i've noticed fps drop when doing box blur. My fps will go down from 4000-5000 fps to 1000-1500 fps. Currently rendering at 853x480 frame buffer and window size.

Is this normal? Oh, and i'm only rendering a basic triangle.
Here's the fragment shader code (pretty much the same from open.gl):

#version 150

in vec2 fTexCoord;

out vec4 finalColor;

uniform sampler2D tex;

const float blurSizeX = 1.0f / 853.0f;
const float blurSizeY = 1.0f / 480.0f;

void main() {
    vec4 col = vec4(0.0f);
    for (int y = -3; y < 4; y++) {
        for (int x = -3; x < 4; x++) {
            col += texture(tex, vec2(fTexCoord.x + x * blurSizeX, fTexCoord.y + y * blurSizeY)) / 49.0f;
        }
    }
    finalColor = col;
}

Thank you in advance.


texts:
I have a problem using spritegroups in pygame. In my situation I have 2 spritegroups, one for humans, one for "infected". A human is represented by a blue circle:

image = pygame.Surface((32,32))
image.fill((255,255,255))
pygame.draw.circle(image,(0,0,255),(16,16),16)
image = image.convert()
image.set_colorkey((255,255,255))

An infected by a red one (same code, different color).

I update my spritegroups as follows:

 self.humans.clear(self.screen, self.bg)
 self.humans.update(time_passed)
 self.humans.draw(self.screen)

 self.infected.clear(self.screen, self.bg)
 self.infected.update(time_passed)
 self.infected.draw(self.screen)

Self.bg is defined:

self.bg = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
self.bg.fill((255,255,255))
self.bg.convert()

This all works, except that when a red circle overlaps with a blue one, you can see the white corners of the bounding box around the actual circle. Within a spritegroup it works, using the set_colorkey function. This does not happen with overlapping blue circles or overlapping red circles.

I tried adding a colorkey to self.bg but that did not work. Same for adding a colorkey to self.screen.


texts:
I'm planing on making a browser game just for fun and to improve my skills, but I have an issue regarding the Software Architecture of the game:

I will be using an ORM to communicate with my database. Let's just talk about a browser game like Ogame or Tribal Wars. What is a model an what not?
Would I make a Model for each Unit Type and each Building Type? Or will I just save the information (for example: which level a certain building is at) in one table and a dataset would look like this:

Village

building1: 10
building2: 5
unit1: 89
...

Which is the approach I should use and how can I determine what feature is a model and which not?

Thank you!

Edit:

I see three approaches in general:

1) Each type has an own model (Main Building, Mine, Barracks). When a structure is built or upgraded the instance is modified (in it's own table). This instance is linked to a village.

2) There is a model for structures. There is an instance for each type. When a structure is built or upgraded a many to many relation is created or updated (with the level as a pivot)

3) I have a property for each building type on my village model.

Notice how this implementation use different amounts of rows in the DB.

Even more interesting: How to handle the units? I guess it's not that efficient if I'd have an instance for each unit, when I'm having 10,000 units per village.

I hope you get what problem I mean


texts: Optimizing Draw calls in MonoGame Android platformer

texts:
I am working on a 2D platformer that is in the final stages of optimization. I have a few different devices for testing, and I am trying to get the best possible framerate on the weaker ones.

On a Nexus 5 I get a constant 60fps, with an occasional hiccup.
On a Galaxy S4 I also get a good 55-60fps
On an original Galaxy S (Vibrant) The frames drop to about 20-25

My question is, given the tile system described below, what can I do to increase the FPS on low-end devices?
And granted the Galaxy S came out years ago, should I even worry about it?

My background consists of 3 scrolling parallax layers.

The world I am drawing in a viewport of 25x15 tiles, at a size of 32x32px per tile, with 3 layers each (32x32x3px).  The camera already culls tiles that are out of view. All tiles are found in one texture, and this is done in a single SpriteBatch call that locates the correct texture location for the tile layer. Code is below:

public void Draw(SpriteBatch spriteBatch, bool upsideDown)
{
    int startX = GetCellAtPixelX( (int)Camera.Position.X );
    int startY = GetCellAtPixelY( (int)Camera.Position.Y );

    int endX = GetCellAtPixelX( (int)Camera.Position.X +
        Camera.ViewportWidth );
    int endY = GetCellAtPixelY( (int)Camera.Position.Y +
        Camera.ViewportHeight );

    for (int x = startX; x <= endX; x++)
    {
        for (int y = startY; y <= endY; y++)
        {
            for (int z = 0; z < MapLayers; z++)
            {
                if ((x >= 0) && (y >= 0) &&
                    (x < MapWidth) && (y < MapHeight))
                {
                    // ...

                    /// The very last parameter in this draw call is
                    /// the draw depth. This draw format will arrange
                    /// layers from front to back (0 = front, 1 = back)
                    /// so we subtract 1 from the z-index as a decimal
                    /// to get the appropriate location:
                    ///     Background      -> 0.7
                    ///     Middleground    -> 0.6
                    ///     Foreground      -> 0.5
                    spriteBatch.Draw(
                        tileSheet,
                        CellScreenRectangle(x, y),
                        TileSourceRectangle(mapCells[x,y].
                            GetLayerIndex((TileLayers)z)),
                        Color.White,
                        0.0f,
                        Vector2.Zero,
                        effect,
                        0.7f - ((float)z * 0.1f)
                    );
                }
            }
        } /// End y loop
    } /// End x loop
}

As you can see, it's not very complex code.  I have checked if my Update calls are slowing the game down, but it's very clearly in the Draw function. When I leave out my call to world.Draw(), fps shoot up to about 50 on the Galaxy S. Also, if I draw only a single layer, I get better performance around 42-45 fps.

I can discard one layer if necessary, but I need at least 2 tile layers. How else can I speed up the draw calls?

I am using MonoGame for Android (XNA)


texts: What are the differences between a skybox and a skydome?

texts: What are the differences/pros/cons between a skybox and a skydome?


texts: When does "frustum culling" actually happen?

texts: So I am a little bit confused, and hopefully not too far off, about when frustum culling actually occurs. Let's suppose that I already have my objects in camera space, and then I have applied the perspective matrix onto it which puts everything into a cube AKA the canonical volume. From there, do I immediately do the "culling" and then simply drop the "z" axis of each point to draw it on 2D image plane? How exactly do I do the culling in the canonical cube volume?


texts:
I don't understand how to listen for collisions in Cocos2D/Box2D.  Say I have two dynamic circle bodies.  One is very small and the other is relatively large.  When the small circle collides w/ the large circle I'd like to do something (play a sound for example).  What's the best way to do this?

I'm currently experimenting w/ the TestPoint method.  Something like:

if(largeCircleBody->GetFixtureList()->TestPoint(smallCirclePoint)){
    // collision happened...
    // play sound etc
}


texts:
I'm making a game where at some point there is a box hanged from the top that the player needs, and to bring it down he need to cut the rope, but i dont know where to begin how to creat the rope and how to make it cute from the point the player cuts it.
I've did some research and found that i should use joints with links and just cut the link that collides with the knife for example, but i never used joints in unity so i'm still lost and would it look like a real rope if i use joints alone or should i add a line rendrer or something like that?


texts: What is better for the overall performance and feel of the game: one setInterval performing all the work, or many of them doing individual tasks?

texts:
This question is, I suppose, not limited to Javascript, but it is the language I use to create my game, so I'll use it as an example.

For now, I have structured my HTML5 game like this:

var fps = 60;
var game = new Game();

setInterval(game.update, 1000/fps);

And game.update looks like this:

this.update = function()
{
    this.parseInput();
    this.logic();
    this.physics();
    this.draw();
}

This seems a bit inefficient, maybe I don't need to do all of those things at once. An obvious alternative would be to have more intervals performing individual tasks, but is it worth it?

var fps = 60;
var game = new Game();

setInterval(game.draw, 1000/fps);
setInterval(game.physics, 1000/a); //where "a" is some constant, performing the same function as "fps"
...

With which approach should I go and why? Is there a better alternative? Also, in case the second approach is the best, how frequently should I perform the tasks?


texts: Adding biome support to procedural landmass generation tutorials

texts:
I've spent the past week studying the procedural landmass generation tutorial series and have been toying around with the source code.

The following is an example of the core Noise module he wrote. Essentially, it accepts some noise settings (seed, octaves, lacunarity, etc) for every "chunk".

I've been trying to figure out on my own how best to implement "biomes" but this is too different than noise systems I've used in the past (they handled octaves/etc internally didn't build those with chunk coordinates, etc).

I know I need different noise settings based on the biome, but I just can't figure out the best way to implement here.

My biggest dilemma is that this logic calculates the octaves/frequency/etc for the entire chunk but those values would be different for different biomes.

Since I need biomes to blend a bit (aka I don't want biomes limited to entire chunks), I need to either:

Use different noise settings for every "coordinate" (which won't work since this code uses one noise settings for the entire chunk)
Calculate the entire chunk once for each biome in it and then somehow "sum" biomes
Ditch this noise entirely with something I'm more familiar with (FastNoise, LibNoise.Unity). I've tried this, but absolutely will not work with the mesh generation he built, so I'd need to rewrite that too.

public static CoordinateProfile[,] GenerateCoordinateProfiles(int mapWidth, int mapHeight, NoiseSettings settings, Vector2 sampleCentre) {
    var profiles = new CoordinateProfile[mapWidth, mapHeight];

    System.Random prng = new System.Random(settings.seed);
    Vector2[] octaveOffsets = new Vector2[settings.octaves];

    float maxPossibleHeight = 0;
    float amplitude = 1;
    float frequency = 1;

    for (int i = 0; i < settings.octaves; i++) {
        float offsetX = prng.Next(-100000, 100000) + sampleCentre.x;
        float offsetY = prng.Next(-100000, 100000) - sampleCentre.y;
        octaveOffsets [i] = new Vector2(offsetX, offsetY);

        maxPossibleHeight += amplitude;
        amplitude *= settings.persistance;
    }

    float maxLocalNoiseHeight = float.MinValue;
    float minLocalNoiseHeight = float.MaxValue;

    float halfWidth = mapWidth / 2f;
    float halfHeight = mapHeight / 2f;

    for (int y = 0; y < mapHeight; y++) {
        for (int x = 0; x < mapWidth; x++) {
            amplitude = 1;
            frequency = 1;
            float noiseHeight = 0;

            for (int i = 0; i < settings.octaves; i++) {
                float sampleX = (x - halfWidth + octaveOffsets[i].x) / settings.scale * frequency;
                float sampleY = (y - halfHeight + octaveOffsets[i].y) / settings.scale * frequency;

                float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
                noiseHeight += perlinValue * amplitude;

                amplitude *= settings.persistance;
                frequency *= settings.lacunarity;
            }

            if (noiseHeight > maxLocalNoiseHeight) {
                maxLocalNoiseHeight = noiseHeight;
            }
            if (noiseHeight < minLocalNoiseHeight) {
                minLocalNoiseHeight = noiseHeight;
            }

            float normalizedHeight = (noiseHeight + 1) / (maxPossibleHeight / 0.9f);
            noiseHeight = Mathf.Clamp(normalizedHeight, 0, int.MaxValue);

            profiles[x, y] = new CoordinateProfile(noiseHeight);
        }
    }

    return profiles;
}


texts: How do I draw anti-aliased holes in a bitmap

texts:
I have an artillery game (hobby-learning project) and when the projectile hits it leaves a hole in the ground. I want this hole to have antialiased edges. I'm using System.Drawing for this. I've tried with clipping paths, and drawing with a transparent color using gfx.CompositingMode = CompositingMode.SourceCopy, but it gives me the same result. If I draw a circle with a solid color it works fine, but I need a hole, a circle with 0 alpha values.

I have enabled these but they work only with solid colors:

gfx.CompositingQuality = CompositingQuality.HighQuality;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.SmoothingMode = SmoothingMode.AntiAlias;

In the two pictures consider black as being transparent.

This is what I have (zoomed in):

And what I need is something like this (made with photoshop):

This will be just a visual effect, in code for collision detection I still treat everything with alpha > 128 as solid.

Edit: I'm usink OpenTK for this game. But for this question I think it doesn't really matter probably it is gdi+ related.


texts: Why doesn't this 2d physics calculation yield the desired jump height?

texts:
I found a formula for gravity and jumping in this article: http://error454.com/2013/10/23/platformer-physics-101-and-the-3-fundamental-equations-of-platformers/

I implemented this formula and proceeded to do some test calculations, but they yield incorrect results. I expected the outcome to be 4, but the test resulted in 3.8. What am I doing wrong? How do I get the number 4?

float deltaTime = 1f / 50f;

float maxJumpHeight = 4;
float timeToApex = 0.44f;
float gravity = (2 * maxJumpHeight) / (timeToApex * timeToApex);

float jumpHeight = 4;
float jumpVelocity = (float)Math.Sqrt(2 * gravity * jumpHeight);

float velocity = -jumpVelocity;
float position = 0;

while (velocity < 0)
{
    velocity += gravity * deltaTime;
    position += velocity * deltaTime;
    Console.WriteLine("Position = {0}", position);
}


texts:
I've got an issue. When (Input.GetMouseButtonUp (0), Speedy script is disabled, thus we cannot enable it again from inside the script like shown below. How can we go around this?

public class  Speedy : MonoBehaviour {

GameObject car;

 if (speed == good)
    {
        GameObject car = GameObject.FindWithTag ("Car");

        if (Input.GetMouseButtonUp (0))
        {
            car.GetComponent<Speedy>().enabled = false;
        }

        else car.GetComponent<Speedy>().enabled = true;
    }
}


texts: How can I prevent the viewport from stretching/distorting?

texts:
Basically, I want to know how I can remove distortion or stretching of the rendered image when the viewport/window size changes.

The following images exemplify the distortion/stretching I'm talking about:

Original Image (Square Window)

Distorted/Stretched Image (Rectangular Window)

Ideally, the second image should display the sphere without the horizontal stretching, and would expose more of the scene to the user to account for the larger window size.

How can this be done?

I'm working with OpenGL to render the image, and I make use of the perspective projection via the calls:

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, window.width/window.height, 0.01f, 100.0f)

The aspect-ratio width/height is in accordance to all of the documents/tutorials I've come across, so I don't expect it to be incorrect.  However, my suspicion is that it is affecting the stretching problem.

After thought

Honestly, as I think about the issue more, I'd led to believe that the solution involves a directly proportional relationship between the fovy (field of view in the y-direction) angle and the aspect-ratio.

Using the above image as a reference, if the width grows (causing a horizontal stretch), it seems very plausible that the fovy angle must increase to cause a vertical stretch that 'fixes' the proportionality of the rendered image.

Likewise, a decrease in width requires a decrease in the fovy angle.

Update:

So, after investigating this further, I've decided to change the way I've set up the viewing frustum like this:

gluPerspective(60 * (float)window.width/window.height, (float)window.width/window.height, 0.01f, 100.0f)

And my expectations were correct, that solved the proportionality issue.  However, it doesn't achieve my desired results.  When the window width increases, the rendered image becomes smaller (but the sphere is indeed circular).  Instead, the sphere shouldn't change size at all;  only the amount of scene that is displayed should change.


texts: I'm trying to make an InputField like the one shown below in Unity. I don't see any way I could do this in Unity. I also want to use google places autocomplete API.I am using Unity v5.6.1f1 .Is this possible?.


texts:
I am making a multiplayer FPS and I am in search of some helpful tips on the perfect FPS camera angle. Because it is a multiplayer, I am making a full body model holding the gun, I find, however, that some of the gun positions (when held naturally) seem awkward when placing the camera on the position of the characters eyes. Moving the camera has other consequences, for example, when moving the camera to a more appropriate fps position, when looking at your feet, it seems that your head is too far right, as your point of view is past your left foot..

Any expert advice?


texts: Best approach to depth streaming via existing codec

texts:
I'm working on a development system (and game) intended for games set mostly in static third-person views.  We produce our scenery by CG and photographic techniques.  Our background art is rendered off-line by a production-grade renderer.

To allow the runtime imagery to properly interact with the background art, I wrote a program to convert from depth output by Mental Ray into a texture, and a pixel shader to draw a quad such that the Z data comes from the texture.

This technique is working out very well, but now we've decided that some of the camera angle changes between scenes should be animated.  The animation itself is straightforward to produce from our CG models.  We intend to encode it to some HD video codec such as H.264.

The problem is that in order to maintain our runtime imagery on the screen, the depth buffer will need to be loaded for each video frame.  Due to the bandwidth, the video's depth data will need to be compressed efficiently.

I've looked into methods for performing temporal compression of depth info and found an interesting research paper here:

http://web4.cs.ucl.ac.uk/staff/j.kautz/publications/depth-streaming.pdf

The method establishes a mapping between 16-bit depth values and YCbCr values.  The mapping is tuned to the properties of existing video codecs in order to maximize precision of the decoded depths after the YCbCr has undergone video compression.  It allows an existing, unmodified video codec to be used on the backend.

I'm looking at how to pull this off with the least possible work.  (This design change was unplanned.)  Our game engine itself is native C++, presently for Win32 and DirectX, although we've worked hard to keep platform dependence segregated because we intend other ports.

We don't have motion video facilities in the engine yet but will ultimately need that anyway for cinematics.  I was planning on using some off-the-shelf motion video solution we can plug into our engine, and haven't chosen one yet.  This new added requirement makes selecting one harder since, among other things, we'll now need to bypass colourspace conversion on one of the streams, and also will need to be playing two streams simultaneously in lockstep, on top of in some cases audio on one of them (for the cinematics).

I'm also wondering if it's possible (or even useful) to do the conversion from YCbCr to depth in a pixel shader, or if it's better to just do it in CPU and separately load the resulting depth values into a locked tex.  The conversion unfortunately does involve branching logic per-pixel.  (There are more naive mappings that don't need branching, but they produce inferior results.)  It could be reduced to a table lookup but the table would be 32MB.

Programming is second-nature to me but I'm not that experienced with pix shaders and have zero knowledge of off-the-shelf video solutions.

I'd therefore be interested in advice from others who may have dealt more with depth streaming, pixel shaders, and/or off-the-shelf codecs, regarding how feasible the proposed application is and what off-the-shelf video systems out there would best get along with this usage case.


texts: In Monogame, why does Rectangle.Offset not work?

texts:
I have the following code in a default Monogame Game project:

protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.Left))
    {
        paddle.Box.Offset(-10, 0);
        Debug.WriteLine(paddle.Box);
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Right))
    {
        paddle.Box.Offset(10, 0);
        Debug.WriteLine(paddle.Box);
    }
    base.Update(gameTime);
}

paddle.Box is a normal XNA Rectangle.

The problem is that the location of paddle.Box does not change after calling any of the Offset() overloads, as debugging confirms. If I just assign a new Rectangle, it works, but Offset (and Inflate(), FWIW) seems to be broken.

What am I doing wrong?


texts: How do I fix this unintentional chromatic aberration on a lightmap?

texts:
Some strange rainbow halos (front and left) appear after computation of a lightmap for direct light. The formula is
dot * dot2 / ( dist * dist ) * dl->intensity

with gamma correction, lightmap is computed as vec3_t and ultimately cropped to 3 bytes. However, brightness of the region in question fit into 255 nicely, and even calculating in byte instead of float beforehand - result in just a subtle "oil painting" effect and does not produce such artifact across entire image.
My best guess is how this artifact appear from base change in a floating point math, but I don't know for sure nor do I understand what exactly is happening.


texts:
I've been creating a game in Java as a bit of a fun side project over the last few months and I've come across a really peculiar problem, take a look at this image:

The game is made up of various entities and elements that are all rendered onto the screen in one big for loop:

for(int i = 0 ; i < level.entityList.size(); i++){
    if(level.entityList.get(i) != null){
        level.entityList.get(i).render(renderer);
    }
}

Now the render function within the entities allow them to render onto a buffered image which is then drawn onto the main canvas using BufferStrategy.getGrapghics().  The problem is sometimes some elements will get rendered out of "Sync" from the rest of the elements. For example, sometimes the "Multiplier x1" and the top left of the screen will shift up a bit or down a bit even though everything is getting rendered onto one plane before being rendered onto the screen.

Can anyone explain why this is happening? (Sorry if this is confusing, I don't really know what to say)

Preview of glitch:
http://www.youtube.com/watch?feature=player_detailpage&v=u9yDlhJV_6I#t=69s


texts: using Mathf.Clamp in Vector3 to restrict object drag

texts:
I'm making a checkers game and I've got a movement controller working to move the pieces. I want to restrict the drag to be within the board. The center of the board is 0,0 so the far left side's x value is -4, top of the boards y is 4, etc...

This is my drag script so far

void OnMouseDrag()
{
        float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
        transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
}

but when I try to clamp my new Vector3's x and y between -4 and 4 like this,

transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x,-4f,4f), Mathf.Clamp(Input.mousePosition.y,-4f,4f), distance_to_screen));

it shoots the pieces way off camera. This may be because don't truly understand Camera.main.ScreenToWorldPoint, is it returning different x,y coordinates than the global ones?


texts: Tweaking and Settings - Runtime variable modification and persistence

texts:
Most companies have an editor, or a variable control system for tweaking stuff in games, but are there any middleware solutions to this problem? I've written two such systems in the past myself, and worked with five, maybe six different ones, but none of them were off the shelf.

Each of these home grown solutions had problems, ranging from having to keep looking up values, to not being able to save the current state of the variables.

Are there any mature Config/Runtime-variable control libraries/apps?

I generally code in C++, but I would think that a mature settings/variables editor would probably be socket based (and therefore language agnostic to some extent) as all current development hardware apart from Nintendo stuff provides a mechanism to talk to servers. The code implementation would also need to be quite simple (I do like the hot_var/TweakableConstants article shared by Oskar, but it's not a package)


texts: Text mesh scaling camera distance relative

texts:
I am searching a fromula that can maintain my text mesh size according to the distance from camera. I want that no matter my camera is near or far from text mesh my text show always with same width an height. I have tried this but the problem is still persist somehow

float  size = (activeCam.transform.position - transform.position).magnitude;
            newLocalScale = new Vector3(size / 108, size / 108, size / 108);
            transform.localScale = newLocalScale;


texts: Does Libgdx being "for Desktop" mean dependency-free native executables?

texts:
I want to clarify whether the Java Framework "LibGDX" can be used to compile games to native executables. The description/tagline says "Desktop/Android/HTML5/iOS Java game development framework".

I presumed that when they say "desktop", what is meant is native executables and not that they'll be .jar that needs JVM/Java installed on the native machine to run.

Can Libgdx games run without a Java dependency?


texts: Changing AnimationOverrideController "sometimes" fails - Unity 5.2.1

texts:
I have the following code, in a menu where you can chose the armor and weapon of a character:

private List<string> armors = new List<string> { "armor1", "armor2", "armor2" };
private List<string> weapons = new List<string> { "weapon1", "weapon2", "weapon3", "weapon4", "weapon5", "weapon6", "weapon7", "weapon8", "weapon9" };

private int  armor_index = 0;
private int weapon_index = 0;

public GameObject avatar_body;
public GameObject avatar_weapon;

void Update() {
         if (Input.GetKeyDown(KeyCode.RightArrow)) nextArmor();
    else if (Input.GetKeyDown(KeyCode.LeftArrow))  previousArmor();
    else if (Input.GetKeyDown(KeyCode.DownArrow))  nextWeapon();
    else if (Input.GetKeyDown(KeyCode.UpArrow))    previousWeapon();
    else if (Input.GetKeyDown(KeyCode.Return))     loadLevel();
}

void nextArmor() {
    if (armor_index < armors.Count - 1)
        armor_index += 1;
    else
        armor_index = 0;

    setArmor();
    setWeapon();
}

void previousArmor() {
    if (armor_index > 0)
        armor_index -= 1;
    else
        armor_index = armors.Count - 1;

    setArmor();
    setWeapon();
}

void nextWeapon() {
    if (weapon_index < weapons.Count - 1)
        weapon_index += 1;
    else
        weapon_index = 0;

    setWeapon();
}

void previousWeapon() {
    if (weapon_index > 0)
        weapon_index -= 1;
    else
        weapon_index = weapons.Count - 1;

    setWeapon();
}

void setArmor() {
    avatar_body.GetComponent<Animator>().runtimeAnimatorController =
        Resources.Load("AnimationControllers/player/"+armors[armor_index]+"/body" ) as AnimatorOverrideController;
}

void setWeapon() {
    avatar_weapon.GetComponent<Animator>().runtimeAnimatorController =
        Resources.Load("AnimationControllers/player/"+armors[armor_index]+"/"+weapons[weapon_index] ) as AnimatorOverrideController;
}

The problem is when I start switching between the weapons, sometimes the sprite showing does not update. Inspecting the GameObject, it is weird, because the Animator Component has successfully updated, but the Sprite Renderer still shows a fixed sprite from the last Animator.

Here are 2 examples:

Here we see that the animator is set for the weapon Gladius, and that the Sprite renderer is looping through all the frames of that animation

Here we can see that even though we have moved to the Flanged mace animator, the Sprite Renderer is still stuck on a sprite of Gladius

The problem is hard to recreate, because it happens just SOMETIMES. If I were to switch back to gladius and then once again back to flanged_mace...

Now it works... but I didn't change anything.

What is going wrong??