texts: Different animations depending on multiple factors on Unity mechanim animator

texts:
I have a character that can carry a single-handed weapon, a two-handed weapon or no weapons at all (weapon hold type int parameter) with a boolean if aiming or weapon down. He can remain idle, he can walk (blend tree from x-y float parameters). Also, as the enemy approaches he can crouch-idle as in if in alert, or as he approaches the enemy he can crouch-walk (boolean parameter).

I can think of 3 ways of handling these variations in postures:

One layer per each weapon variation: a layer for "two-handed weapon" and one for "single-hand weapon". In each of them, there would be an "idle" state for a normal idle animation, one state for "idle crouch", one state for "walk" for normal walking animation, one state for "walk crouch" for alert mode, etc. A "crouch" boolean parameter would tell whether to idle/walk standing upright or not.

the other way would be to have one single layer, and handle all variations with several boolean parameters: "walk", "crouch", "one-handed", "two-handed". Example: If "walk" is false, "crouch" is true and "single-handed" is true, the character would remain still, in a crouch position, with only one hand carrying the weapon.

Another way could be to have one layer per animation type (one for the different idles, one for the different walks, etc.) and switch the layer weight depending on the character's animation to play.

Which of the three (or any other possibility?) do you think scales best when more animations (or parameters) are added to the state machine? Or to rephrase it better: what is the best way to organize the animator given three (or more) parameters?

For example, I may want to add another boolean if is shooting or not (for recoil) and I can already see the spaghetti mess in the animator... SO I think there must be a better way to organize all of this.

Thanks!


texts: Make Love2D load resource from inside the .love file

texts:
I've just made my first (very simple, ugly) game in Love2D.  The game works fine when run directly off my hard drive.  However, when I package it up as a .love file, I get the following message:

  Error: Could not open file resources/stormclouds.bmp. Does not exist.
  stack traceback:
    [C]: ?
    [C]: in function 'newImage'
    [string "main.lua"]:46: in function 'load'
    [string "boot.lua"]:304: in function <[string "boot.lua"]:302>
    [C]: in function 'xpcall'

The "resources" folder does exist within my directory structure (resources/stormclouds.bmp), and the game runs fine when its not packaged up.

The line of code responsible for this is:

bg = love.graphics.newImage("resources/stormclouds.bmp")

How can I make this line work for my packaged file?


texts: No sound effects until DirectX reinstalled in my Monogame project; what DLL to ship?

texts:
Environment: Windows 10 (fresh install), using Monogame 3.6 (same goes for 3.5 for this matter) on DirectX projects. Problem: I can’t hear any sound effect unless I reinstall DirectX.

Before reinstalling DirectX, there is no exception or status information I could use to trace why the sound is not audible. After reinstalling, it just works. Same code, even same binary.

I don’t want my users to have to reinstall DX. This will be awkward as Win10 comes with DX pre-installed.

So I wonder if someone knows which additional DX libraries I may include in project folder so that the sound effects are audible without reinstalling DX?


texts:
I'm not exactly sure how I should ask this question, and so the title may be misleading - I am not asking if I should use a list or a stack or a vector or a queue - but how I should go about keeping track of said storage object.

For example, let's say I have some object that would represent the game itself, and the game used state objects to tell what state it was in(IE, playing, paused, titlescreen, gameover screen, etc etc):

class Game
{
    //Constructors and what not
    private:
    stack<States*> states;
};

And then each state would keep track of the objects that it contained.

class States
{
    //Constructors and whatnot
    private:
    list<Mob*> listOfMobs;
    list<Bullet*> listOfBullets;
};

Now, what if I have a Mob spawn new Mobs, or have a Mob fire a bullet? I definitely don't want to pass the State itself down to all Mobs - I'd have dozens(or more) of copies of the State wandering around, which does not seem very wise. In the same sense, passing down the list of Mobs or bullets does not seem like the best idea either.
So, how should I handle this? I don't want to use global variables, and in the same way I wouldn't like to use a singleton pattern to keep track of it all - but I don't see very many other options. I might just be stuck thinking inside the proverbial box, though. How does everyone else handle tracking the objects in their game?


texts:
I'm working on a tile based game and already got a generator working. But it doesn't seem to be smooth enough to look realistic.

Here's the code I'm using:

for (int i = 0; i < width; i++)
        {
            float y = ClassNoise.PerlinNoise1D(i, 2f, 4);
for(int j = 2048+y;j<height;j++)
{
  tiles[i][j] = new Tile(i,j);
}
}

public class ClassNoise
{
    public static float Noise(int x)
    {
        x = (x<<13) ^ x;
        return (float) ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
    }
    public static float PerlinNoise1D(float x, float persistence, int octaves)
    {
        float total = 0;
        float p = persistence;
        int n = octaves - 1;

        for (int i = 0; i <= n; i++)
        {

            float frequency = (float) Math.pow(2, i);
            double amplitude = Math.pow(p, i);
            total += InterpolatedNoise(x * frequency) * amplitude;
        }

        return (int) total;

    }

    private static float InterpolatedNoise(float x)
    {
        int integer_X = (int) x;
        float fractional_X = x - integer_X;

        float v1 = SmoothNoise1D(integer_X);
        float v2 = SmoothNoise1D(integer_X + 1);

        return CosineInterpolate(v1, v2, fractional_X);

    }

    public static float CosineInterpolate(float a, float b, float x)
    {
        float ft = (float) (x * Math.PI);
        float f = (float) ((1 - Math.cos(ft)) * 0.5);

        return a * (1 - f) + b * f;
    }
    public static float SmoothNoise1D(int x)
    {
        return Noise(x)/2  +  Noise(x-1)/4  +  Noise(x+1)/4;
    }

}

How can I make this terrain generator smoother?

EDIT:

It currently looks like this (The terrain on the screenshot isn't the full terrain it's just the terrain on the screen):


texts: How do I set a scene up for two players?

texts:
I´m finishing a game in Unity, but I have a new requirement: make it multiplayer. I will do this by splitting the screen and running two instances.

Is there a way to instance a scene twice at the same time, and render them two a different part of the screen? Alternativley, what is the best approach to achieve this?


texts: Anyone know of other unique playable archetypes?

texts:
Well I like to play games that give me a wide breath of options. For most part I see games implementing certain archetypes like the usual RPG trinity (tank, DPS and healer).

So far the most archetypes I've seen are in fighting, card and strategy games.

Fighting games archetypes I've seen are:

Rush down (GG Accent Core Venom, Kof 2k1 heidern)
Grappler (SF Zangief)
Zoning (SF Dhalsim, KoF Billy Kane)
Ranged(GG Dizzy)
Trapper (GG testament)
Well rounded (SF Ryu)
Status effects (GG Baiken)
Chance (GG Faust)
Counter (GG Baiken)
Time (Arcana Heart Anutpada, Psychic force Wong, Jojo's Bizarre adventure Dio)
Positions control (Arcana Heart Dieu Mort).

Card Games: Burn, milling, OTK, counter, graveyard based, trapping (Yu-gi-oh), remove from play, restrict.

Strategy games: League of legends have a number of them so I'll just link to their wiki. Note not all are archetypes though, add to that builders as well.

So any other that you guys might know that is worth mentioning?


texts: Sparse voxel octree for 3d pathfinding and Manhattan distance

texts:
I've been learning about using sparse voxel octree for 3d pathfinding based on Daniel Brewer's chapter in Game AI and his talk at GDC 2015.
One aspect that I'm really confused about is exactly what is considered to be a neightbor of a cell in the tree, and whether using Manhattan distance is alright or not. Let's assume that all the cells are of the same size and consider some cell C. How many neightbors will it have - 6, one for each side of the cube, or 27-1=26, all the cubes "touching" our chosen cell at least in one vertex?
It seems the former 6, but I don't see how that doesn't cause problems if we calculate distances between centers of the cells - it induces a manhattan norm, and there's lots of situations where that fails. I have some intuition why it might not be an issue if you do some type of "post processing" on the found path, but it could simply fail quite badly in finding a good path.
Brewer has mentioned using Manhattan distance throughout the talk as well to allow for easier computations, but: 1, it seems like a very problematic thing to me and 2, it seems to me like Manhattan distance is already being used when moving across neightboring cells of same size, which I would assume where the bulk of the expensive computation happens.
//
EDIT: Adding some examples of where it seems to me that Manhattan distance fails:

Green path corresponds to the good paths, red to the wrong paths. Technically the the green paths should be drawn in jagged way, as on the grid you can only move vertically/horizontally, but you can imagine that if we zoomed really close to them, that is really what they look like - it's just not visible from this distance.
sI -> eI is an example of the general issue with something like Dijsktra's - the red path has the same length as the green path in Manhattan distance and could get chosen. It would probably work fine with A* if we use something like euclidean distance for the Heuristic, since it will greedily go as close to the obstacle as possible.
sI -> eII shows the same problem, but fails with A* too.
I can imagine that both of the above are not huge issues - the pathfinding finds a general path which is good enough - when it comes to the agent actually following the path, they could for example set its next "target" as the furthest point on the path it can travel to directly (check a raycast/spherecast), or even do a few raycast checks along the line between the last point it can reach directly and the next one - the blue line in the image. We would set the local "target" to be a point on the blue line that is furthest away from the reachable point.
sII -> eIII doesn't seem like something that can be fixed like I described in the paragraph above. A* will simply find the wrong red path.


texts:
I implemented variable jumping in unity for an endless running game.
My question, how can I make the jump frame rate independent?

My algorithm

if ( keyDown ){
isJumping = true
ySpeed += jumpStep*Time.deltaTime;
if( ySpeed > maxJumpHeight )
    ySpeed = maxJumpHeight;
   //JUMP OVER
}
// Apply gravity
ySpeed -= ( currentGravity * Time.deltaTime ) ;
// set position
playerSprite.transform.localPosition = new Vector3(0,currentPos.y+ySpeed,0);

This varies on different devices, What I am trying to do that, whatever the device is, the jump should always be the same on a given time.

What if i do this in FixedUpdate? Will it work fine?


texts: Get the length of an animation from the Animator

texts: How do find the length of an animation that is included in the Animator attached to a GameObject?


texts: Change shadervalues for different Meshes in Three.js

texts:
Hey I am writing a Shader for Three.js.

My goal is to have multiple objects with the same shader and each object should have a color set on the object that is then given to the shader. The goal is to have multiple "units" (think of an RTS game) each with the team color.

I red through a couple of documentation pages and am not really sure how to handle that. I looked into https://threejs.org/docs/#api/materials/ShaderMaterial.

I have tried:

changing a uniform but from my limited knowledge and trial and
error I came to the conclusion that I can not change a uniform value
during a drawcycle.
change the uniform in onBeforeRender which gave me an error that v
was not defined

I am not sure how to go on now. In the ShaderMaterial Documentation is written:

  You're recommended to update custom Uniform values depending on object and camera in Object3D.onBeforeRender because Material can be shared among meshes, matrixWorld of Scene and Camera are updated in WebGLRenderer.render, and some effects(ex:VREffect) render a scene with private their own cameras.

So did I just change the values wrong and it actually works with a uniform that changes? In this Github issue someone wanted to draw meshes in different colors and got suggested to create different materials for each mesh (https://github.com/mrdoob/three.js/issues/1532). But that would kill the idea of having one shader per unit regardless of the team.


texts:
I have been making a 2d platformer using Python with PyGame. It has all be going good, but I have stumbled accross many problems with collision detection. Here they are:

You can't go through objects that have the exact space for you to go through
You can go through the ceiling (very weird)

The code I have is very big and I think that, since it involves multiple classes, I should post it on GitHub, so here is the link to my repository: https://github.com/pta2002/SuperBros.

But just for reference, here is my colliion detection method:

def detectCollisions(self, x1, y1, w1, h1, x2, y2, w2, h2):

    if x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2:
        return 1

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2:
        return 2

    elif x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return 3

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return 4

    else:
        return 0

and here is my update method:

def update(self, gravity, block_list):
    if self.velocity < 0:
        self.falling = True

    collision = 0
    blockX, blockY = 0, 0
    self.canMoveRight = True
    self.canMoveLeft = True

    for block in block_list:
        collision = self.detectCollisions(self.x, self.y, self.width, self.height,
         block.x, block.y, block.width, block.height)

        if not collision == 0:
            blockX = block.x
            blockY = block.y
            break

    if not collision == 0:
        if self.falling:
            self.falling = False
            self.onGround = True
            self.velocity = 0
            self.y = block.y - self.height
        else:
            if collision == 2:
                self.canMoveRight = False

            if collision == 1:
                self.canMoveLeft = False
    else:
        self.falling = True
        self.onGround = False

    if not self.onGround:
        self.velocity += gravity

    self.y -= self.velocity
    if (self.canMoveRight and self.xvel > 0) or (self.canMoveLeft and self.xvel < 0):
        self.x += self.xvel

    if self.jumping:
        if self.onGround:
            self.velocity = 8
            self.onGround = False

    if self.cur_image >= self.num_images - 1:
        self.cur_image = 0
    else:
        self.cur_image += 1


texts:
I'm implementing ominidirectional shadow mapping for point lights. I want to use a linear depth which will be stored in the color textures (cube map). A program will contain two filtering techniques: software pcf (because hardware pcf works only with depth textures) and variance shadow mapping. I found two ways of storing linear depth:

const float linearDepthConstant = 1.0 / (zFar - zNear);
//first
float moment1 = -viewSpace.z * linearDepthConstant;
float moment2 = moment1 * moment1;
outColor = vec2(moment1, moment2);
//second
float moment1 = length(viewSpace) * linearDepthConstant;
float moment2 = moment1 * moment1;
outColor = vec2(moment1, moment2);

What are differences between them ? Are both ways correct ?

For the standard shadow mapping with software pcf a shadow test will depend on the linear depth format.
What about variance shadow mapping ?

I implemented omnidirectional shadow mapping for points light using a non-linear depth and hardware pcf.
In that case a shadow test looks like this:

vec3 lightToPixel = worldSpacePos - worldSpaceLightPos;
vec3 aPos = abs(lightToPixel);
float fZ = -max(aPos.x, max(aPos.y, aPos.z));
vec4 clip = pLightProjection * vec4(0.0, 0.0, fZ, 1.0);
float depth = (clip.z / clip.w) * 0.5 + 0.5;
float shadow = texture(ShadowMapCube, vec4(normalize(lightToPixel), depth));

I also implemented standard shadow mapping without pcf which using second format of linear depth: (Edit 1: i.e. distance to the light + some offset to fix shadow acne)

vec3 lightToPixel = worldSpacePos - worldSpaceLightPos;
const float linearDepthConstant = 1.0 / (zFar - zNear);
float fZ = length(lightToPixel) * linearDepthConstant;
float depth = texture(ShadowMapCube, normalize(lightToPixel)).x;
if(depth <= fZ)
{
     shadow = 0.0;
}
else
{
     shadow = 1.0;
}

but I have no idea how to do that for the first format of linear depth. Is it possible ?

Edit 2: For non-linear depth I used glPolygonOffset to fix shadow acne. For linear depth and distance to the light some offset should be add in the shader. I'm trying to implement standard shadow mapping without pcf using a linear depth (-viewSpace.z * linearDepthConstant + offset) but following shadow test doesn't produce correct results:

vec3 lightToPixel = worldSpacePos - worldSpaceLightPos;
vec3 aPos = abs(lightToPixel);
float fZ = -max(aPos.x, max(aPos.y, aPos.z));
vec4 clip = pLightProjection * vec4(0.0, 0.0, fZ, 1.0);
float fDepth = (clip.z / clip.w) * 0.5 + 0.5;
float depth = texture(ShadowMapCube, normalize(lightToPixel)).x;
if(depth <= fDepth)
{
     shadow = 0.0;
}
else
{
     shadow = 1.0;
}

How to fix that ?


texts: Unity Application.LoadLevel freezes the game on Android device

texts:
I'm developing a game using Unity. The game has a single level and after the player wins/loses, I simply want to reload the same scene. Here's the code I'm using:

private void OnLevelFailed()
{
    IsGameStarted = false;
    Debug.Log("LEVEL FAILED");
    Invoke("RestartLevel",5);
}

void RestartLevel()
{
    Application.LoadLevel(Application.loadedLevelName);
}

When running this code on the editor, everything seems fine and the scene reloads as intended. However, when I build the game for Android and run it on a device (an LG G3), the game simply freezes. I used adb logcat to see the logs of any exceptions or errors if there were any but to no luck. I also suspected if the Invoke call was causing the problem and replaced it with simply the method call, but that didn't solve the problem either.

Anyone have any idea why this might happen?


texts: I am making a defence game. Naturally, this means that there needs to be objects following a path on the screen. I want to make it a strict path from one point to another to another. I could use an array of vertices, but i need some help. Can someone please show me some code that could help me with this? Thanks.


texts: Can this script be edited to create a "shotgun" type spread when firing? [Top down shooter]

texts:
I have this code and I'd like to add a shotgun to the game by slightly modifying the code. I've looked online for any example but everything I find is for FPS not a TDS.

void Shoot ()
{
    timer = 0f;

    gunAudio.Play ();

    gunLight.enabled = true;

    gunParticles.Stop ();
    gunParticles.Play ();

    gunLine.enabled = true;
    gunLine.SetPosition (0, transform.position);

    shootRay.origin = transform.position;
    shootRay.direction = transform.forward;

    if (Physics.Raycast (shootRay, out shootHit, range, shootableMask))
    {
        EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
        if(enemyHealth != null)
        {
            enemyHealth.TakeDamage (damagePerShot, shootHit.point);
        }
        gunLine.SetPosition (1, shootHit.point);
    }
    else
    {
        gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
    }
}

I have a basic understanding of most of this code. I don't quite understand how shootRay.direction understands transform.forward means always the front of player. As DMGregory stated adding a variable of some sort that runs through a for loop firing multiple different angles (or simply different coordinates if making angle rays is over my head) is the route I first thought of but I cannot find a way to implement it. I'm having issues with understanding how to manipulate ray coordinates because they cannot be changed by floats which is the extent of my current knowledge of problem solving.


texts: 2D Physics Engine for Platform Games - Riding on a Platform

texts:
I have a number of questions relating to using a 2D physics engine in a platform game, but one main one that I'm grappling with at the moment.  I managed to somewhat integrate the Physics2D.Net engine into a Scrolling Game Development Kit 2 project.  I'm very pleased with the performance and the realism of the physics.  However, I've lost some things that my original SGDK2 physics engine (oriented more specifically to platform games) made easier:

Riding on a platform is very difficult now.  This is my main question.  It's not difficult to implement, but difficult to play.  Assuming I even do manage to get the player onto a platform (which is hard enough in itself), as soon as the platform moves, the player falls off because there's not enough friction between the player and the platform or something.  Do I just need to tweak things like friction, inertia, linear velocity dampening and the like to make it easier to ride on a platform, or is there something fundamentally difficult about riding on platform is the "real" world?  I've tried reducing the force applied to the platform that makes it move (so it would allow more time for the rider to match the platform's velocity), but then that's not enough force to keep the rider aloft, and the platform sinks to the ground.  I'm simply applying forces to move the platform.
What is the best way to stop the platform from rotating?  I've tried setting the Angular momentum and the angular position to 0 on each frame, but this can result in little twitches that cause anything on the platform to spring into the air a bit, just long enough to fall off.
Running along the ground: How do most platform games with realistic 2D physics implement the player?  My player is currently a square, but will often tumble and spring into the air due to friction hitting one of the corners.  My guess is that the player should be a circle and always drawn upright.  Is this standard practice, or is there another way?  If I use a circle I expect that riding a platform will be even more difficult!  The player will roll right off.  I'm thinking of Little Big Planet, which also seemed to keep the player on the ground pretty well.  Do I just have to put a lot of velocity damping on the player, or something like that, if I want to keep them grounded too?
Since SGDK2 is a tile-based engine/IDE, I have writen code that analyzes all the shapes of the terrain/tiles and turns them into physics bodies with infinite mass (merging them horizontally, but not vertically where appropriate; merging two directions was too difficult for me to figure out because I couldn't figure out how to trace and represent the hole in a torus-like formation).  Is that a good way for a platform game to implement something for the sprites to interact with to represent the solid ground?  Am I better off turning each tile into a physics body (few simple shapes, many bodies and internal surfaces between tiles), or merging them as I am doing (fewer bodies, but more shapes that are more complex)?
I'm having a hard time figuring out the optimal vertex subdivision level and grid spacing to use.  I don't really understand these concepts and documentation on Pysics2D.Net is sparse to non-existent as far as I can tell.  I am generally subdividing to about 6 and using a grid spacing of about the same.  My sprites and tiles are mostly 32x32 units (pixels), all square for the moment.


texts: How can I Intercept object with a circular motion

texts:
I am creating a 2d space game and need to make the spaceship intercept a planet. I have working code for straight line intercepts but cannot figure out how to calculate the planets location in a circular orbit.

The game is not scientifically accurate so I am not worried about inertia, gravity, elliptical orbits, etc.

I know the spaceships location and speed and also the planets orbit (Radius) and speed


texts: Question about JPanel "transition" for Java Swing

texts:
I want to make like a sort of main menu (in GUI).
When the user clicks the start button, the screen transition into another "screen" (JPanel). This image will make it easier to understand.
http://i.imgur.com/Cfdry.png

Currently, I have a MainMenu extends JPanel and that gets added into a driver class with a JFrame. I can't figure how to switch to another class like Game extends JPanel.
So when the user clicks the start button in MainMenu, I want it to somehow hide itself and the Game to show itself.
Thanks.


texts: I'm trying to set a GameObject(plane) to be positioned at my camera's farplane. I plan on using this billboard as a sort of dynamic skybox. How would I create a billboard that is fixed to my camera's farplane?


texts: Problem with impulses in my physics engine

texts:
I'm currently developing a small 3D impulse-based physic engine for a CS project.  It uses GJK for collision detection and is kind of stable at the moment.  Nevertheless, I'm not satisfied with my collision response as rigid bodies appear to gain more and more momentum with each bounce, although only under some configurations.

I use Newton’s Law of Restitution (pictured immediately below) for instantaneous collisions with no friction.  I checked this formula again and again, and I also checked if the magnitude of the contact normal is 1, and all seems fine.  The direction of the bounce and the induced rotation are convincing but the impulse is just sometimes too strong.

I think my problem may lie within the impulse application part; in my mind, the impulse is the force necessary to separate two touching points of two bodies plus a certain magnitude depending on the coefficient of restitution (0.7 in my tests).  I compute an impulse for each detected contact point and apply it at the contact position.

For example if a cube falls right to the floor, there will be 4 impulses, each one at a vertex of the bottom face of the cube.  For each of the four contacts, I do something like this:

J = computeImpulse(contact)
A.applyImpulse(J, contact.pos)
B.applyImpulse(-J, contact.pos)

I'm a bit confused.  Is this the correct approach, or should I apply half of the impulse to each body?  Or, should I rather apply a fraction of the impulse depending of the mass of the bodies?  Or, is the problem just somewhere else (e.g., in the formula)?

I don't know if someone has an easy answer for me, as it's a rather specific problem, but thank you for your help.  :)


texts: How to get drawn Image width/height on the screen with openGL ES on Android?

texts:
I need to know how to get drawn image length and width.

I have this code so far where I draw Radar in left top corner with hard-coded coordinates:

int _SRC = R.drawable._item;

...

float vertices[] = {
            0f,  0f,  0.0f,
            0f,  2.0f,0.0f,
            2.0f,0f,  0.0f,
            2.0f,2.0f,0.0f
    };
...

addRadarToView(0,240);

...

public void addRadarToView(float x, float y) {
    this.x = x;
    this.y = y;
}

 ...

private void updateScreenData(float screenWidth, float screenHeight){
    // takes screen Height and Width
    this.mScreenWidth = (screenWidth > 0) ? screenWidth : 1f;
    this.mScreenHeight = screenHeight;
    wRatio = 10f/mScreenWidth;
    hRatio = mScreenHeight/10f;
}

 @Override
public void loadTextures(GL10 gl) {
    Log.e(LOG_TAG, "loadTextures");

    InputStream is;

    is = mContext.getResources().openRawResource(_SRC);

    Bitmap bitmap = BitmapFactory.decodeStream(is);

    try {
        is.close();
        is = null;
    } catch (IOException e) {
    }

    gl.glGenTextures(TEXTURE_COUNT, textures, 0);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();

}

 protected void drawRadar(GL10 gl){
    gl.glPushMatrix();
    try {
        float transx =  (wRatio * (x));
        float transy =  (mScreenHeight*wRatio) - (wRatio * (y)) - 1/hRatio;
        // Log.e(LOG_TAG, "transx: " + transx + "; transy: " + transy + "; sprite.x: "+  sprite.x + "; sprite.y: " + sprite.y);

        gl.glTranslatef(transx, transy, 0.0f);

        //###########  draw ##############

        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, floatBufferArray[mFrame]);

        //update();

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        //###############################

    } catch (NullPointerException e) {
    }
    gl.glPopMatrix();
}

I used addRadarToView(0,240); to set x=0 and y= 240;

So as I see x represents left border of vertices. When 240 is y that represents bottom border. Strange.

[EDIT]

In canvas i used something like:

 int srcX = currentFrame * width;

Rect  src = new Rect(srcX, 0, srcX+width, height);
Rect  dst = new Rect(x, y, x+width, y+height);
canvas.drawBitmap(bitmap, src, dst, null);

Where width and height are:

bitmap.getWidth();
bitmap.getHeight();

Please, help me to sort it out.

Thanks,


texts: MMORPG Entitiy handling on different maps

texts:
Is this a good approach for a MMORPG entity handling on different maps?

Map Structure and entity existece:

A map is basically a parent node in a scene graph. There's one map for each town, room etc. In each of these maps the entities or actors (split up into localplayer/NPC/remoteplayer) exist with their own coordinates in respect to map size. Each map has it's own position in worldmap, it's id and it's own update() method which calls update() on each entity.

Server:

Server has 2 Hashmaps with key being map_Id and value being according map reference. One is a pool for every map possible, the other one is currently active (or populated) maps. Also an eventqueue is available containing 2 queues, one for current events and one for new events resulting from current event processing. Events are collected in between ticks by a event fetcher thread accepting incoming events from remote (inbox) and are distributed by a extra event distributor thread (outbox).

Each tick/render server processes the eventqueue and given a actorupdate event calls update() on each affected map (calling update() on every entity). Before/while this processing happens each relevant event in inbox is being distributed to each relevant client. Relevant means the event is of interest to the particular client (e.g. events concerning actors on map1, each client on map1 is then relevant) and the event was not sent by receiver client itself.
Each n-ticks sanity check is sent to all clients.

Client

Client stores current map and possible new map preloaded in reference (if player is in transition zone). Events are processed similar to server but include local only events like AnimationStarted and a event fetcher thread saves all incoming events from server in an inbox.

Each tick the inbox is being put in local current eventqueue, local built server relevant events like ActorMove are being send to the server and all events are being processed just like server does with 2 queues putting new queue into current queue etc. Regardless of own latency client will at some point in time have the sanity check in inbox and must process it.


texts: Getting started with cross-platform game development

texts:
I am looking for a starting place to develop a crossplatform OpenGL game that runs on Mac, PC and potentially Linux.  The difficulty is that I don't want to use an existing graphics library.

I've done a lot of work with OpenGL in C++ for Windows.  I have never developed anything for Mac.  I plan to develop most of the Windows game and leave my project open with abstraction so that I can later implement Mac-specific code.

Is there anything that works radically different in Mac and Linux than in Windows?  With Windows for example, I use DirectInput and XInput to capture controllers and keyboard, window messages to capture mouse and typing.  Where can I find some type of "translation guide"?  Also, do I still need to consider endianness?

How can I design my project so that I can load it up in Visual Studio 2008 and easily compile it in OSX and Linux IDEs?  Since I own Visual Studio, I'd like to use that for my Windows development, rather than switch to a cross-platform IDE.


texts: Problem generating multiple shadow maps in a loop

texts:
I've successfully implemented shadow mapping for a specific direction as you can see in the image below:

Now I want to do omnidirectional shadow mapping but without using a cube map.

My first step was to turn my frame buffer object to an array of frame buffer objects and the same with my texture map (so I can get 6 shadow maps, one for every direction). This is the plan, but I'm stuck much earlier.
Replacing my variable framebufferFBO with framebufferFBO[0] and my texture variable depthMap with depthmap[0] the program runs exactly the same ( as expected ) .
However, when I try to do the following, and I mean only the following, as I'm already in the debugging phase , all I get is a black image .

for (int i = 0; i < 2; i++) {
    glGenTextures(1, &depthMap[i]);
    glBindTexture(GL_TEXTURE_2D, depthMap[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadow_width, shadow_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO[i]);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap[i], 0);
    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

The only change is that it goes on for 2 loops. If I just do one loop my first shadow map works fine. If I leave it as it is the map you see in the first picture gets ruined.

So what is wrong with this loop? Am I doing something that is not allowed?

Edit: It seems that the problem is glDrawBuffer(GL_NONE).If it's not executed in the second loop, my first shadow map is still fine.


texts: How should I plan the inheritance structure for my game?

texts:
I am trying to write a platform shooter in C++ with a really good class structure for robustness. The game itself is secondary; it is the learning process of writing it that is primary.

I am implementing an inheritance tree for all of the objects in my game, but I find myself unsure on some decisions.

One specific issue that it bugging me is this:

I have an Actor that is simply defined as anything in the game world. Under Actor is Character. Both of these classes are abstract.

Under Character is the Philosopher, who is the main character that the user commands. Also under Character is NPC, which uses an AI module with stock routines for friendly, enemy and (maybe) neutral alignments.

So under NPC I want to have three subclasses: FriendlyNPC, EnemyNPC and NeutralNPC. These classes are not abstract, and will often be subclassed in order to make different types of NPC's, like Engineer, Scientist and the most evil Programmer.

Still, if I want to implement a generic NPC named Kevin, it would nice to be able to put him in without making a new class for him. I could just instantiate a FriendlyNPC and pass some values for the AI machine and for the dialogue; that would be ideal.

But what if Kevin is the one benevolent Programmer in the whole world? Now we must make a class for him (but what should it be called?). Now we have a character that should inherit from Programmer (as Kevin has all the same abilities but just uses  the friendly AI functions) but also should inherit from FriendlyNPC.

Programmer and FriendlyNPC branched away from each other on the inheritance tree, so inheriting from both of them would have conflicts, because some of the same functions have been implemented in different ways on the two of them.

1) Is there a better way to order these classes to avoid these conflicts? Having three subclasses; Friendly, Enemy and Neutral; from each type of NPC; Engineer, Scientist, and Programmer; would amount to a huge number of classes.

I would share specific implementation details, but I am writing the game slowly, piece by piece, and so I haven't implemented past Character yet.

2) Is there a place where I can learn these programming paradigms? I am already trying to take advantage of some good design patterns, like MVC architecture and Mediator objects. The whole point of this project is to write something in good style.

It is difficult to tell what should become a subclass and what should become a state (i.e. Friendly boolean v. Friendly class). Having many states slows down code with if statements and makes classes long and unwieldy. On the other hand, having a class for everything isn't practical. 3) Are there good rules of thumb or resources to learn more about this?

4) Finally, where does templating come in to this? How should I coordinate templates into my class structure? I have never actually taken advantage of templating honestly, but I hear that it increases modularity, which means good code.


texts:
I want to draw my pre-rendered depth map to the scene.

I get my depth value in the following way:

basically (Pixel Shader)

// Depth is stored as distance from camera / far plane distance, 1-d for more precision
output.Depth = float4(1-(input.Depth.x / input.Depth.y),0,0,1);

where (Vertex Shader)

output.Position = mul(input.Position, worldViewProjection);
output.Depth.xy = output.Position.zw;

(input = output of Vertex Shader)

and store it in a RenderTarget2D

depthTarg = new RenderTarget2D(GraphicsDevice, viewWidth,
                viewHeight, false, SurfaceFormat.Single, DepthFormat.Depth24, samples, RenderTargetUsage.DiscardContents);

But somehow, when I draw that (Single), I get this result:
(displaying rgb)

channel r:

(all black)

channel g:

channel b:

channel a:

Why is there data in every color channel althrough i only defined a value on the red parameter (and 1 on a, but you can somehow see the outlines of the model, so it cant be all 1)

And surprisingly, the b channel looks almost like what I am looking for, but has strange lines in it which stay at the same distance to the camera if I move it.


texts:
I'm making a little top down 2D dungeon crawler, and have pretty much fallen over at collision detection with my dungeon walls. I have figured out how to stop my player sprite at the walls, but I'm having trouble with the seams of the vertical walls. Horizontal walls, for some reason, are giving me absolutely no issue.

I store a bunch of rectangles representing the dungeon walls, and for each entity that is of the type RigidBody.Type.Moving, I collision check using a projection of where the entity will be based on its current X & Y velocity (against all rectangles, at the moment).

Here is my collision detection code:

var dt = (float) gameTime.ElapsedGameTime.TotalSeconds;
var rb = entity.GetComponent<RigidBody>();
var body = rb.Body;

// We only want to do collision checks for bodies that are moving.
if (rb.Type != RigidBody.Type.Moving) return;

// Don't collision check against itself!
var rectangles = CollisionWorld.Instance.Bodies.Where(b => b != body);
foreach (var rectangle in rectangles)
{
    // Work out where the entity is going to be next with its current velocity
    // and store it as a rectangle to collision check on.
    var projectedBody = new Rectangle(
        (int)(rb.Position.X + rb.Velocity.X * dt),
        (int)(rb.Position.Y + rb.Velocity.Y * dt),
        body.Width, body.Height);

    // If we have a collision, continue. Otherwise move on.
    if (!Collision.DoesCollide(projectedBody, rectangle)) continue;
    var side = Collision.CalulateCollisionSide(projectedBody, rectangle);

    if (side == Collision.Side.Top || side == Collision.Side.Bottom)
    {
        rb.Velocity.Y = 0;
    }
    if (side == Collision.Side.Left || side == Collision.Side.Right)
    {
        rb.Velocity.X = 0;
    }
}

I have tried finding the collision intersection, and using it to offset the player's position. by that and that kinda works, but then the sprite is all jittery whenever it collides. I've been bashing my head against this for a couple of days, now.

Why would the seams between each vertical tile be causing my sprite to get stuck?


texts: Alpha blending sometimes gives the wrong color?

texts:
I've got a method for alpha blending:

public static int alphaBlend(int c1, int c2) {
        int a1 = (c1 & 0xff000000) >>> 24;

        int r1 = (c1 & 0x00ff0000) >> 16;
        int r2 = (c2 & 0x00ff0000) >> 16;

        int g1 = (c1 & 0x0000ff00) >> 8;
        int g2 = (c2 & 0x0000ff00) >> 8;

        int b1 = (c1 & 0x000000ff);
        int b2 = (c2 & 0x000000ff);

        float src_alpha = ((float)a1) / 255.0f;

        int red   = (int) ((r1 * src_alpha) + (r2 * (1.0f - src_alpha)));
        int green = (int) ((g1 * src_alpha) + (g2 * (1.0f - src_alpha)));
        int blue  = (int) ((b1 * src_alpha) + (b2 * (1.0f - src_alpha)));

        return (a1 << 24) | (red << 16) | (green << 8) | blue;
    }

But sometimes this gives the wrong color (I guess because I don't use the second color's alpha). Could anyone explain how to fix this?


texts: How to design a turn-based game which is easy for humans but difficult for AI?

texts:
Until recently, Go used to be of the last bastions of turn-based no information-hiding games where world-class human players could not be defeated by computers. But now this bastion has fallen, as the program AlphaGo managed to beat one of the world top players.

However, Go was never designed as a game which is hard for AI. It was developed thousands of years ago. Being hard for computers was an unintentional side-effect of the game design, not a stated design goal.

What game mechanics make a turn-based strategy game without information hiding hard for AI, yet still playable for humans?

In case someone wonders "Why is this question also relevant for video game developers"?

because it shows us how to design competitive multiplayer games where players can not cheat by using an AI assistant.
For single player games it shows us what to avoid when we plan to add an AI opponent later.


texts: How check if an arbitrary given mesh is a single closed mesh?

texts: I'm building a space game where it is allowed for the player to insert his own mesh to be his spaceship. The problem I'm facing is that a ship must be a Polygon Mesh. The player will then be able to place thing inside the ship to make it behave. My question is, given an arbitrary mesh (a set of vertices and triangles), how check if it is a polygon mesh (no holes, with a clear inner side)?


texts: How to create a joint, where the rotation of one object is relative to the other?

texts:
I would like to create a top down view scene, with one rectangle (top) is on top of an other (base). There is a joint, where these two objects are connected.
The one on the top should be able to freely rotate, but if the base rotates, its rotation should be changed as well, because it should behave as if it is on top of it. If the joint is at the center of both objects, then the top one should rotate like this:
Δ top rotation = Δ time * ( top angular velocity + base angular velocity )

If the joint is not at the center of the objects, then it is more complicated than that. How is it possible to define a joint like that in Box2D?
This is a testbed example with the joint. Notice, that the top one is not rotating:
#include "test.h"

class RelJoint : public Test
{

    b2Body* base;
    b2Body* top;
    b2RevoluteJoint* m_joint;

public:

    RelJoint() {

        m_world->SetGravity(b2Vec2(0.0f, 0.0f));

        {

            b2PolygonShape shape;
            shape.SetAsBox(1.f, 0.5f, b2Vec2(0.0f, 0.0f), 0.0f);

            b2BodyDef bd;
            bd.type = b2_dynamicBody;
            b2Body* body = m_world->CreateBody(&bd);
            body->CreateFixture(&shape, 5.0f);

            body->SetAngularDamping(1.f);

            base = body;
        }

        {

            b2PolygonShape shape;
            shape.SetAsBox(0.5f, 0.25f, b2Vec2(0.0f, 0.0f), 0.0f);

            b2BodyDef bd;
            bd.type = b2_dynamicBody;
            b2Body* body = m_world->CreateBody(&bd);
            body->CreateFixture(&shape, 5.0f);

            top = body;
        }

        b2RevoluteJointDef revoluteJointDef;
        revoluteJointDef.bodyA = base;
        revoluteJointDef.bodyB = top;
        revoluteJointDef.collideConnected = false;

        revoluteJointDef.localAnchorA.Set(0, 0);
        revoluteJointDef.localAnchorB.Set(0, 0);

        m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&revoluteJointDef);

    }

    void Step(Settings& settings) override {
        base->ApplyTorque(3.f, true);

        Test::Step(settings);
    }

    static Test* Create()
    {
        return new RelJoint;
    }

};

static int testIndex = RegisterTest("Joints", "Relative", RelJoint::Create);

I tried to combine b2RevoluteJointDef with b2FrictionJointDef. It looks promising, but unfortunately if I apply torque to the top body only, the base starts to rotate too, which I would like to avoid.


texts: Unexpected Execution Order in Unity (uNet)

texts:
I made a little game in Unity. It works fine in the Editor. But if I run the build version I get a NullReferenceException.

This problem does only appear if the build-version-client hosts the game.

No problems if the BUILD-version plays as client or server only.
No problems when played in EDITOR

I have a class (CharacterSpawner) that is meant to run on the server only.

public static CharacterSpawner instance;

...

public void Awake()
{
    instance = this;
    print("Character Spawner Awake");
}

[Server]
public void SpawnCharacter(NetworkConnection owner)
{
    GameObject character = Instantiate(characterPrefab, randomSpawnPoint, Quaternion.identity) as GameObject;
    NetworkServer.SpawnWithClientAuthority(character, owner);
}

I have another class (Player) that should send a Command to the server in order to spawn a character right at the beginning.

void Start()
{
    if (isLocalPlayer)
    {
        CmdSpawnCharacter();
    }
}

[Command]
public void CmdSpawnCharacter()
{
    CharacterSpawner.instance.SpawnCharacter(connectionToClient); // throws NullReferenceException
}

'instance' is here the only thing that could cause the NullReferenceException, because connectionToClient would not cause a NullReferenceException even if it was null! This means the instance is not set yet.

As problem I can think that the Start-method in the Player-script is called before the Awake-method in the CharacterSpawner Script. Because if I call CmdSpawnCharacter like this:

Invoke("CmdSpawnCharacter", 0.5f);

It works perfectly, but that is not the way I want to do this.

I even changed the priorities of the scripts, but without success.

QUESTION: Why does Start() gets called before Awake() gets called? This does not line up with the docs http://docs.unity3d.com/Manual/ExecutionOrder.


texts: Is there anyway to disable the script "gameplay" from running once you start the simulation?

texts:
Was following the tutorial in this video https://oxmond.com/how-to-make-multiple-copies-of-a-gameobject/ on how to duplicate object.
I want to modify my code I learned from this tutorial https://www.youtube.com/watch?v=OR0e-1UBEOU&t=4178s so that the bird will increase its size proportion to the distance travel and when scale>certain value, it break into 2 identical bird object that possess the same properties as the first one. I already did the part size increase in proportion to the distance travel. Now I create an empty game object and attach the script "explode" together with prefab of the bird object to it but how to write the proper code to carry out the function if the main bird object is destroyed then it run the code "explode" to duplicate bird?
   using UnityEngine;
   using UnityEngine.Assertions.Must;
   using UnityEngine.SceneManagement;

   public class Bird : MonoBehaviour

{Vector3 OldPosition;
Vector3 DistanceDifference;
float TotalDistance = 0;
Vector3 _initialPosition;
private bool _birdWasLaunched;
[SerializeField] private float _launchPower = 500;

void start()
{
    OldPosition = transform.position;

}

private void Awake()
{
    _initialPosition = transform.position;

}

    void Update()
    {

    if (_birdWasLaunched &&
             GetComponent<Rigidbody2D>().velocity.magnitude > 0.1)
    {
        DistanceDifference = transform.position - OldPosition;
        TotalDistance += DistanceDifference.magnitude;
        OldPosition = transform.position;
        transform.localScale = new Vector3(0.2f * Mathf.Abs((TotalDistance * 0.2f)), 0.2f *Mathf.Abs(TotalDistance * 0.2f) , TotalDistance*0.5f);

    }

    if (transform.position.y > 20.00 ||
        transform.position.y < -20.00 || transform.position.x > 23 || transform.position.x < -23)
    {
        string currentSceneName = SceneManager.GetActiveScene().name;
        SceneManager.LoadScene(currentSceneName);

    }
    }

void OnMouseDown()
{
    GetComponent<SpriteRenderer>().color = Color.red;

}

private void OnMouseUp()
{
    GetComponent<SpriteRenderer>().color = Color.white;
    Vector2 directionToInitialPosition = _initialPosition - transform.position;
    GetComponent<Rigidbody2D>().AddForce(directionToInitialPosition * _launchPower);
    GetComponent<Rigidbody2D>().gravityScale = 1;
    _birdWasLaunched = true;

}

private void OnMouseDrag()
{
    Vector3 newPosition =    Camera.main.ScreenToWorldPoint(Input.mousePosition);
    transform.position = new Vector3(newPosition.x, newPosition.y);

This the 2nd script to duplicate the bird but i'm not sure what the correct codes I have to put in if the 1st game object destroy, then it duplicate 2 bird?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Explode : MonoBehaviour
{
 public GameObject Bird;

// Update is called once per frame
void Update()
{
    (if Destroy(Bird))
    GameObject BirdClone = Instantiate(Bird);
}
}


texts: Getting a TileMap wrapping as a toroid on player movement

texts:
[libgdx version 1.9.13 - Desktop Game]
This question seems to have been asked many times, but I have yet to find a decent solution. I want to display a map without edges, where the player moves in all directions on a 'world' which is toroidal.
I load my tiles into cells of an OrthogonalTiledMapRenderer, which I then render. This gives me a map which draws in the game window - works fine - but it has edges. The player can walk up to the edge of map.
So my questions:

How do I get a tiled map to draw without edges (I.E. no background color around edge of tile map, as per attached screen shot, which shows character about to walk off the map)

How do I then make the map toroidal - so the player moves off left map edge and is moved to right edge. Same for top/bottom. I can set the players coordinates to do this, but screen 'jumps' to the other edge.

So if the player continually presses a single up/down/left/right key, eventually they will come back to their starting position.


texts: How can I avoid tons of if/else statements dealing with settings?

texts:
I am creating a sudoku game using the android sdk. I have a PreferenceActivity filled with different settings, such as "Highlight all digits" or "activate the visual helper".
The problem is that I am trying to avoid using the if else pattern everywhere in my code in order to check if each settings is activated to execute a specific code.
I am looking for the best pattern that could help me to handle my different settings.
My code is pretty clear(I think), I have a Grid class containing all the grid information and a Game view, that handles inputs and interacts with the Grid class.


texts: Panda3d handling collisions on walls created in blender

texts:
Edit 2 : Updated code, so runnable zip isn't the same as the copied section bellow (though all that has changed is that part in run_me.py)

Edit: Runnable zip with source files, sorry: https://dl.dropboxusercontent.com/u/12781104/Collisions.zip

Right now I am trying to create a small room for my character to walk around in, it works decently but will walk through walls, I am having difficulty setting up the collision logic to stop the character from walking through walls. The problem is properly creating the collision plane to line up with the walls (is there a way to do this in blender?)...

Code so far that has to do with wall collisions

 [Removed imports]

    ....

    self.cTrav = CollisionTraverser()
    robotCHandler = CollisionHandlerQueue()
    robotWallCHandler = CollisionHandlerPusher()

    WALL_MASK=BitMask32.bit(2)

    ralphStartPos = (0, 0, 0)
    self.ralph = loader.loadModel("robot.x")
    self.ralph.reparentTo(render)
    self.ralph.setScale(1)
    self.ralph.setPos(ralphStartPos)
    self.ralph.setCollideMask(BitMask32.allOff())
    # setup tube to suround robot
    #(robot is 3 height, by 1.5, 1.5)
    cTube = CollisionSphere(0, 0, 0, 3)

    robotCollisionNode = self.ralph.attachNewNode(CollisionNode('robotcnode'))
    robotCollisionNode.node().addSolid(cTube)
    robotCollisionNode.node().setFromCollideMask(WALL_MASK)
    robotCollisionNode.node().setIntoCollideMask(BitMask32.allOff())

    self.environ = loader.loadModel("room2.x")
    self.environ.reparentTo(render)

    root = self.environ.find("**/Root")
    walls = root.findAllMatches("**/Plane*")

    for w in walls:
        # set it to the same bitmask so the collider collides
        w.node().setIntoCollideMask(WALL_MASK)

    robotWallCHandler.addCollider(robotCollisionNode, self.ralph)

    self.cTrav.addCollider(robotCollisionNode, robotWallCHandler)

The bottom line is what I am most confused about, how do I get the collision plane properly setup, do I just have to hard code the points or is there something easier (maybe the geom nodes?)?


texts: In the Unity Editor, how do I find prefabs containing a specific component?

texts:
I want to find all prefabs in the project that contain a specific Component?

I only need this in-editor; no need at runtime.

If they are in added to the Scene, I can right-click and Find References in Scene. However, this is entirely unhelpful since I have a lot of prefabs in the project which aren't added to the Scene and I'd need to search those too…


texts: Using Delta for a stopwatch, delta too fast than real time seconds

texts:
I search for methods to create a stopwatch on libgdx and came across with this:

public void trigger(float delta){

    playTime += delta;
    playTimeRounded = ((double)Math.round(playTime * 100) / 100);
    Gdx.app.log("deltaTime", delta + "");
}

But its not accurate and its much faster. How can i create an accurate stopwatch?


texts: Where do I store (or how do I refer to) textures for custom blocks?

texts:
I'm making my first foray into Minecraft modding on Ubuntu using Minecraft Forge. I'm finding it a little hard to get started as many of the tutorials seem to refer to older versions of Minecraft (e.g. that use the BaseMod base class, which now appears to be deprecated).

I've created a simple block type:

package net.minecraft.block;

import net.minecraft.block.*;
import net.minecraft.block.material.*;

public class RolyBlock extends Block {
    public RolyBlock(int par1, Material par2Material) {
        super(par1, par2Material);
    }
}

and added the following static initialiser to the Block class:

public static final Block rolyBlock = new RolyBlock(174, Material.rock)
                                      .setHardness(1.5F)
                                      .setResistance(10)
                                      .setStepSound(soundStoneFootstep)
                                      .setUnlocalizedName("rolyBlock")
                                      .setCreativeTab(CreativeTabs.tabBlock)
                                      .setTextureName("roly_block");

I created a 256x256 PNG file called roly_block and placed it in Forge's MCP folder, in the same location as the other textures. However, when I start Minecraft (v. 1.6.5) via Eclipse, it is unable to locate the texture:

2014-03-14 11:38:34 [SEVERE] [Minecraft-Client] Using missing texture,
unable to load: minecraft:textures/blocks/roly_block.png

I suspect this is because I put the texture in the directory

forge/mcp/temp/src/minecraft/assets/minecraft/textures

(where I found the other textures) where this temp folder is presumably a decompiled version of the Minecraft 1.6.5 .jar file. I can't actually remember how I ended up with this folder, though.

My question is: how do I add a new texture to my Eclipse mod development environment? Must I rebuild a .jar each time, and if so how? Or can I have Minecraft load textures from a directory?

(I'm a complete Minecraft newbie, so there are many things about the configuration/dev environment for Minecraft that are confusing me. For example if I run recompile.py from Forge's MCP folder, I get a swathe of errors relating to IconRegister not being found.)


texts:
I'm creating a simple game for the iPhone using Cocos2d.
I'm having a hard time understanding how add real objects to a tiled map.

I know that you can add an object-layer to the tiled map and set the position of it,
but I'm not sure how to define WHAT object it should be.

For example, if I'm creating a simple Super Mario Bros. I want to add different blocks to the map, one should hold a star, one should hold a coin, and so on.

How should I define what object it is?

So my question, how do I correctly create class-objects in a tiled map?


texts: Vertex data split into separate buffers or one one structure?

texts:
Is it better to have all vertex data in one structure like this:

class MyVertex
{
  int x,y,z;
  int u,v;
  int normalx, normaly, normalz;
}

Or to have each component (location, normal, texture coordinates) in separate arrays/buffers? To me it always seemed logical to keep the data grouped together in one structure because they'd always be the same for each instance of a shared vertex and that seems to be true for things like character models (ex: the normal should be an average of adjacent normals for smooth lighting).
One instance where this doesn't seem to work is other kinds of meshes like say a cube where the texture coordinates for each may be the same but that causes them to be different where the vertices are shared.

Are they normally kept separate? Won't this make them less space efficient if there needs to be an instance of texture coordinates and normals for each vertex (they won't be indexed)?
Can OpenGL even handle this mixing of indexed (for location) vs non-indexed buffers in the same VBO?


texts: Calculating damage with damage mitigation/amplification curve/function

texts:
Let's say instance A is attacking instance B for N damage. I want to calculate the ideally expected damage if those instances have damage mitigation/amplification depending on target's current HP.

Instance B has an ability that it will take less damage as its HP gets lower. It could be like a (half of) sin curve, or maybe some complex function. So the formula look something like this:

$$damage = damage_{raw} \cdot ({1 \over 4} + {3 \over 4} \cdot \sin ({\pi \over 2} \cdot {hp \over hp_{max}}))$$

B will have 75% damage mitigation at 0% HP and 0% at 100% HP.

What I want to here is to chop the damage into infinite pieces and apply each to B so B can fully utilize its ability, and get the value after the process.

Also I'd like know how I'll calculate it when A has a similar ability that also changes the damage, like, increasing damage if the target has lower HP. Also there can be a case both of the instances have a variety of damage changers.

I think it's related to calculus but I have no knowledge about it.


texts: Sprite/Object/Room limits in GameMaker 8.1?

texts: I know about GameMaker Studio’s limitations for sprites, objects, rooms, and other assets (https://help.yoyogames.com/hc/en-us/articles/230407528-GameMaker-Studio-2-Trial-Limitations), but I can’t find anything about if there are similar limitations in GameMaker 8.1, which I also have on my computer. What are the limits for sprite, object, background, and room count in the Lite and Standard versions of GameMaker 8.1, if there are any?


texts: Passing by pointer-reference in blueprints with C++ definitions

texts:
MyFunction( Class *& foo )

Inside a derivative BP of the above C++ class:

foo shows up as an output rather than an input.

Why?


texts: Using Content.Load() in a class that is not derived from Game

texts:
I have a class (SpriteManager) that is not derived from Game || DrawableGameComponent || GameComponent so I use my custom methods.

When my game starts, it runs that class. My question is, how to use Game.Content.Load in a class that is not derived from any of the classes above.

I tried declaring a variable in my SpriteManager of type Game but when I use it, it returns null or an InvalidOperationException.

My variable Game:

Game game

This is my LoadContent() method:

spriteBatch = new SpriteBatch(GraphicsDevice);

//my player sprite
player = new PlayerMovement(game.Content.Load<Texture2D>(@"Images/collisionPlayer"), game.Content.Load<Texture2D>(@"Images/" + body[0]), new Vector2(150, 150), new Point(20, 35), 0, new Point(0, 0), new Point(0, 0), new Point(1, 11), 2f, 2f, 65f);

This is my SpriteManager constructor:

public SpriteManagerGeneral(GraphicsDevice graphicsDevice)
{
    GraphicsDevice = graphicsDevice;
    LoadContent();

}

And this code is in my Game class:

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(this.GraphicsDevice);
    spriteManager = new SpriteManager(GraphicsDevice);
}


texts: Similarities and Differences between LWJGL and Android OpenGL?

texts: So, since I’ve been working a lot with LWJGL recently, I’ve come to learn that Android has native OpenGL support. So, what does this mean for me? Is OpenGL handled the same way it is in LWJGL? What’re the larger differences between the two?


texts: Why do my point lights disappear when another nearby light is above 1.85 range?

texts:
I'm making a game with a dungeon setting in Unity 3D. Many torches line the walls. I'm using a point light over each torch to simulate the flame. However, when two torches are across from each other, and one goes above the 1.85 range, the other disappears completely, giving off no light.

What might be causing this?


texts:
I have the 3rd person controller in my game, which moves with the WASD keys.
But since I am developing for a mobile release, I want touch controls.

I have already the touch control-script in a new script-file, but attached to the same 3rd person controller-prefab.

When I swipe right for instance, I want Unity to trigger the D-key etc.

How can I do that?

...
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
    if (delta.x > 0)
        //trigger D?
    else if (delta.x < 0)
        //trigger A?
}
...


texts: Shooting the closest enemy that you can see

texts:
I'm trying to make my main character aim at the closest enemy that he can see.

My issue is with the close range criterion taking priority. If the enemy is near the player but the player can't see him, I'd like the player to look for another enemy inside his range.

As you can see in the image, There is an enemy behind the wall. The player is not aiming at him because he can't see him. So far this is correct.

But the player is also ignoring the enemy in front of him because he's busy rejecting the one behind the wall.

What he should do is aim at the one in front of him, because he can see him and he is inside the player's range.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;
public class clickme : MonoBehaviour
{

private NavMeshAgent mAgent;
public float mark, ToPoint;
public bool actives, seeEnemy;
private Transform target;
public float range, enemyDistance; // range is player eyes field.
public float speed = 5.0f;
public Transform aiming_point, playerEye;
private GameObject[] targets;

void Start()
{
    targets = GameObject.FindGameObjectsWithTag("enemy");
    target = targets[0].transform;
    seeEnemy = false;
}

void Update()
{

    if (mAgent.remainingDistance <= mAgent.stoppingDistance)
    {
        actives = false;
        if (actives == false && playerEye == true && target != null)
        {

            if (enemyDistance <= range)
            {
                Vector3 dir = target.position - transform.position;
                Quaternion lookRotation = Quaternion.LookRotation(dir);
                Vector3 rotation = Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * speed).eulerAngles;
                transform.rotation = Quaternion.Euler(0f, rotation.y, 0.0f);
            }

        }
        else  {

        }

    }
    else   {
        actives = true;

    }

    updateTarget();

} // end update

void updateTarget()
{
    GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
    float shortesDistance = Mathf.Infinity;
    GameObject nearestEnemy = null;
    foreach (GameObject enemy in enemies)
    {
        float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
        if (distanceToEnemy < shortesDistance)
        {
            shortesDistance = distanceToEnemy;
            nearestEnemy = enemy;

            RaycastHit hit; // can I see my closent enemy or not ?
            if (Physics.Linecast(playerEye.position, nearestEnemy.transform.position, out hit))
            {
                Debug.DrawLine(playerEye.position, nearestEnemy.transform.position, Color.blue, range);

                if (hit.collider.tag == "enemy")
                {
                    seeEnemy = true;
                    print(" I can see enemy !");

                }
                else
                {
                    seeEnemy = false;
                    print("No enemy here!");

                }
            }
        }

    } // end foreach

    if (nearestEnemy != null && shortesDistance <= range && seeEnemy == true)
    {
        target = nearestEnemy.transform;
        aiming_point = target.transform.Find("aim");
        enemyDistance = Vector3.Distance(transform.position, target.transform.position);
    }
    else
    {
        target = null;
        aiming_point = null;
        seeEnemy = false;
        enemyDistance = 0;
    }

} // end target

}


texts:
I have a PickupTarget object in front of my FirstPersonCharacter which is used for 'holding' picked up object. Somehow, it doesn't work; when I click on the object (Axe) it just stays on the ground.

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

public class PickUp : MonoBehaviour {

    public Transform target;

    void Update () {

    }

    void onMouseDown() {
        this.transform.position = target.position;
        this.transform.parent = GameObject.Find ("FirstPersonCharacter").transform;
    }

    void onMouseUp() {
        this.transform.parent = null;
    }
}

I have added PickupTarget as a target of script in Axe object:

This is the structure of my Axe object.


texts:
I have a character that starts in the air and applying gravity to it to collide with platforms in my level. At the start, the character gradually gains speed descending until it collides with a platform. After colliding, I display text letting me know if collision is detected (character touching the ground is true). But when I push the 'W' key, the character doesn't jump. It's worth noting that there is no dedicated ground zero as the level has platforms at different heights.

void Player::update(const std::vector<std::string>& layerData, float deltaTime)
{
    // check if player touches ground
    mOnGround = collideWithLevel(layerData);

    if (mInputManager->isKeyDown(SDLK_w)) // press W to jump
    {
        jump(deltaTime);
    }

    land(deltaTime);
}

void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower * deltaTime;
        mOnGround = false;
    }
}

void Player::land(float deltaTime)
{
    if (!mOnGround)
    {
        mVelocity.y += mGravity * deltaTime;
        mPosition.y += mVelocity.y;
    }

    if (mOnGround)
        std::cout << "On ground" << std::endl; // fires
}


texts: Bounding box should rotate - Skews instead

texts:
I have a method to rotate a sprite's bounding box around the center of the sprite (the sprite rotates and I need the bounding box to rotate with it. The sprite is rectangular).

Instead of being rotated, the bounding box is skewing wierdly. When the angle is 0 - the bounding box is a perfect rectangle. But when the angle changes, the bounding box is getting gradually skewed.

All of this happens in the object's move() method. This method is called every cycle of the game-loop. What I'm trying to do is this:

Move the sprite in the direction the user chose. (x += dx, y += dy).
Get the coordinates of the new center of the sprite.
Get coordinates for the four vertices of the not-rotated-version
of the sprite.
Manipulate these coordinates, so they are now the vertices of the
rotated sprite.

The coordinates that step 4 gives me, are used to create the bounding box (and temporarily draw it on the screen so I can see).

Somewhere, this fails. As I said, the bounding box doens't rotate. Instead, it skews (and maybe also rotates, not sure).

What could be the problem?

Code:

public void move(){

// Advance sprite.
x += dx;
y += dy;

// Get the new center point of the sprite.
centerx = x + width/2;
centery = y + height/2;

// Get the 4 vertices of the non-rotated version of the sprite.
xcoo[0] = (int) x;
xcoo[1] = (int) (x + width);
xcoo[2] = (int) (x + width);
xcoo[3] = (int) x;

ycoo[0] = (int) y;
ycoo[1] = (int) y;
ycoo[2] = (int) (y + height);
ycoo[3] = (int) (y + height);

// Manipulate each vertex, so it fits the rotated sprite.
for(int z=0;z<4;++z){

    xcoo[z] -= centerx;
    ycoo[z] -= centery;

    xcoo[z] = (xcoo[z] * Math.cos(Math.toRadians(angle)) - ycoo[z] * Math.sin(Math.toRadians(angle)));
    ycoo[z] = (xcoo[z] * Math.sin(Math.toRadians(angle)) + ycoo[z] * Math.cos(Math.toRadians(angle)));

    xcoo[z] += centerx;
    ycoo[z] += centery;

}

}

Help would be very appreciated. Thank you


texts: Are there any branching dialogue editors (preferably for Mac)?

texts:
I'm currently looking for a branching dialogue editor that allows me to prepare all the dialogue, export it into an XML format that then can be parsed by Unity 3D.

The only editor I found until now is Chat Mapper, which is Win only. Is there something similar for Mac?

Even if there is nothing for the Mac – what would be other alternatives to Chat Mapper, if any?


texts:
I am developing an FPS Offline Multiplayer Game.

In my game the player rotates using mouse input.

I want to rotate using Touch input.Touch to Swipe screen and player can rotate or Camera will be same.

This is my MouseLook Script

public class FPSMouseLook : MonoBehaviour {

public enum RotationAxes{ MouseXAndY, MouseX, MouseY }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivity = 4;
public float aimSensitivity = 2;

[HideInInspector]
public float sensitivityX = 15;
[HideInInspector]
public float sensitivityY = 15;
//float minimumX = -360;
//float maximumX = 360;

public float minimumY = -80;
public float maximumY = 80;

float rotationY = 0;

[HideInInspector]
public float currentSensitivity;

void Update (){

        if (Time.timeScale < 0.01f)
            return;
        if (axes == RotationAxes.MouseXAndY) {
            float rotationX = transform.localEulerAngles.y + Input.GetAxis ("Mouse X") * sensitivityX;

            rotationY += Input.GetAxis ("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3 (-rotationY, rotationX, 0);
        } else if (axes == RotationAxes.MouseX) {
            transform.Rotate (0, Input.GetAxis ("Mouse X") * sensitivityX, 0);
        } else {
            rotationY += Input.GetAxis ("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3 (-rotationY, transform.localEulerAngles.y, 0);
        }

        sensitivityX = currentSensitivity;
        sensitivityY = currentSensitivity;

}

public void Recoil(float amount){
    rotationY += amount;
}
}

I want to convert this into Touch input when touch to screen and swipe the finger then rotate player.

I tried doing this but it's didn't work for me. if anyone knows how to use this script based on Touch Input then it's really helpful to me. Thank in Advance


texts: Unity2D TileMap Collider Update Optimization

texts:
I'm currently working on a 2D tile-based side-scroller (similar to Terraria). I am using Unity's TileMap feature to draw tiles onto the screen and have my player collide with them as if they were blocks. A 2-dimensional array of ints (8000 on a side for a total of 64M values) is generated to signify tile values, and tiles are placed in the world corresponding to this array at runtime. I have also implemented a rudimentary chunk system which loads tiles in 10x10 areas at runtime relative to the player's position. I'm using Unity 2019.1.0f2 Personal (the latest build of Unity at the time of posting this.)

Whilst attempting to optimize my game's performance, I noticed that the "Physics2D.TilemapColliderTileUpdate" function is causing extreme lag spikes in the game whenever I load in new tiles. This is expected, as adding new tiles will cause the tilemap to recalculate its collider shape. But this is taking up way too much CPU for my needs. In the profiler picture shown, my game runs at a solid 700-1000 FPS normally, but shoots down to 5-20 FPS when new chunk(s) are loaded (the orange lag spikes are where the collider update function is called.) This causes an extreme amount of stutter, and is even more present in an executable build where the unity editor is not in the way of things (in build, FPS jumps down to 2-6 FPS.) I know that this is the case since I can disable the tilemap collider, and of course, there is no more issues. But obviously I wish to have this collider, so that solution will not work.

I was just wondering if there is any way to calculate a tilemap collision shape or different collider system entirely in order to make the game more playable? I can't seem to find any resources on this subject, and am more towards the intermediate side of things when it comes to coding experience. I have attached a picture of some profiling I did when running the game (the CPU usage graph shows a far more tame result as opposed to the usual bad performance), as well as a link to the project folder for my game so the project can be ran an assessed (all of my world generation and chunk management is done in the World.cs script, FYI.) Thank you for your help!

Project folder link:
https://drive.google.com/open?id=14YSvDviZ2_KpZAflaCXZ2JYM-kxSiIu_


texts: Why aren't linked lists more common data structures for enemies?

texts:
I was recently listen to a talk that Jonathan Blow gave, you can find it here.  In the talk, he was talking about what data structures he (and he seemed to imply many others) use, and why.  Which is to say that he simply used arrays to store data, and use the naive approach to find data in it, meaning iterate through the array until you found what you wanted, assuming it wasn't in a performance critical place in the code.  He gave the example of loading data from a wad file in doom, which while fast, still took that naive approach (at least according to the talk, I haven't looked at the source code since I have not a clue to where I should begin).  The reason he gave for this was because while it may be slightly slower to do things the naive way, it's not much, and in many cases, not noticeable, so it's better to optomize how much work you can get done in your lifetime, than to make things a millisecond faster, again, assuming it's not in your physics engine or something like that.

All this seems well and good, except I have one question, why not linked lists rather than arrays?  Sure, if you had to make your own linked list class, I would be on board, but in c++ anyway, assuming your using STL, you only need to declare the type as a list, rather than as a vector, and use iterators to loop over it, rather than looping an index.

The advantages of using a linked list though seem much greater, for example, if you can be guaranteed that nothing is going to be removed from it while your iterating, you don't need to have locks around it, because adding data doesn't have the possibility of moving everything (or is that a bad assumption).  Also, in general, moving data is slow, although this could potentially be avoided if you know the size of your data by reserving the space.

Another advantage is when you do remove data, you just tell the list to remove it, and it just needs to change a few pointers, and call a destructor, which can be done pretty quickly.  But to remove something from an array/vector, you have to either shift everything back one, or possibly add a flag saying that it has been deleted.  (Or, another possibility if you don't care about the order of the data, is move the data at the end index, to the data in the now deleted position).  Either way, this seems like it is a lot of extra, unneeded work, or potentially too slow.

I did take a look around and found this, which claimed that a lot of older developers didn't want to use STL because it wasn't mature enough.  Also, older games AFAIK, used C rather than C++, which also doesn't have STL.  And I could see a case there for using arrays rather than linked lists, because you would have to make your own (which while simple enough to do, could potentially lead to many more errors).

I also read that it's a bad idea to create iterators in Java (due to the garbage collector), but that idea seems moot in languages such as C++, where there isn't a garbage collector, and I would imagine that linked list iterators are pretty lightweight (admittedly probably not as lightweight as vector iterators though).  Or is this also a bad assumption, and it's better/faster just to use an index in your loop, and increase that.


texts:
Can someone give me a detailed
explanation about frame rate and fps concepts?


texts: How can I debug a GameObject's rotation?

texts:
I have a model of a dragon, with an animation of it flying.  When I play the animation in the Animator's preview, the dragon flies in a straight line, but when I run it in-game, it flies around in circles about 10 units in diameter.

If the turning isn't coming from the animator, it has to be coming from somewhere else, but I have no idea where.  There aren't any scripts on the dragon that would influence it like that.  Is there any way to discover what's causing my dragon to turn?  (It's times like this that I really miss the ability to set a memory breakpoint on an object when working in .NET.  That would make this trivial!)


texts: MonoBehavior Script that uses UnityEditor - Best practice for Location?

texts:
I've created a script which helps me auto-generate a GameObject prefab. It uses some UnityEditor, so it can't be used at runtime (and its not meant to be).

Normally, a script like this I would put in the "Editor" folder.

However, since it needs to be attached to a GameObject as a Component to do its thing, I'm not sure where I should put it. I can't store it in the Editor folder, because Unity yells at me and says I'm not allowed.

Are there any best practices defined for things like this?


texts:
Okay so I've been working on GPU skinning skeletal animations.

I need help assessing what is going on here. Looks like the animations are completely mirrored

What are the possible issues? I've been looking at it for so long I'm numb to it. Maybe some fresh eyes will be able to pinpoint what it could be?

Thanks in advanced.

This is in Blender(how is should look):

This is what it looks like in my engine:


texts:
I'm trying to create a mobile joystick using this free package from Unity. Here is the code for rotation which seems to be working fine. I just want to clamp the rotation to +90 or -90 degress. I have tried using the mathf.clamp function but the plane(player) completes a full rotation.

public Joystick joystick;
float rotateVertical;
float rotateHorizontal;

float minClamp = -90.0f;
float maxClamp = 90f;

void Update()
{
    rotateVertical = Mathf.Clamp(joystick.Vertical * 1f, minClamp, maxClamp);

    rotateHorizontal = Mathf.Clamp(joystick.Horizontal * -1f, minClamp, maxClamp);

    transform.Rotate(rotateVertical, 0, rotateHorizontal);
}

If I change the value of minClamp to 0, then the plane doesn't rotate on the negative x axis but is still  able to complete a full rotation on the positive x axis. Can someone please help me?


texts: How to orient hands(or spine) to always look at some target?

texts:
I am building an FPS game in Unity 3D everything was going cool but when I tried to implement aiming for the rifle everything just broke.

1): I have an IK setup which triggers when you equip weapon, this IK only calculate the hand position and orientation needed to hold the gun and after that the IK system disables itself, basically I am using IK for getting the proper hand position on different guns.

2): Once hands are positioned correctly on the gun then I rotate the hands(or spine, which will rotate hands and head with it) with the mouse to look up, down, right and left.

3): Handgun is very easy to handle, equip it and rotate the arms, arms are almost straight along the z-axis so I just rotate them on the y-axis to aim upward and downwards.

4): With the rifle, I can calculate the hand position and rotation to hold the rifle easily but (because static animation pose of holding he rifle is little oriented to make the player little realistic) when I rotate arms they rotate weirdly.

I checked in the editor by changing the y-axis of the rotation and found that only y-axis can't rotate the arm the way I want and to rotate it that way other axis must change their values. I searched a bit and found that it is a situation called as Gimbal Lock which is very common with euler rotations, I tried many things but still can't fix it.

Original Code:

        leftArm.transform.localEulerAngles = new Vector3(leftArm.transform.localEulerAngles.x,
        leftArm.transform.localEulerAngles.y + (currentCamRotX + offset),
        leftArm.transform.localEulerAngles.z);

        rightArm.transform.localEulerAngles = new Vector3(rightArmFPS.transform.localEulerAngles.x,
        rightArmFPS.transform.localEulerAngles.y + (currentCamRotX + offset),
        rightArmFPS.transform.localEulerAngles.z);

It works great with Handgun but not with Rifle.

I read about and tried following but in vain:

    //Method 1: Failed
    var target = camera.GetChild(0).GetChild(0);
    var direction = target.position - rightArmFPS.position;
    var toRotation = Quaternion.FromToRotation(rightArmFPS.up, direction);
    rightArmFPS.rotation = Quaternion.Lerp(rightArmFPS.rotation, toRotation, Time.deltaTime * 5);

    //Method 2: Failed
    var targetForward = target.position - spine.position;
    targetForward.Normalize();

    var rotAxis = Vector3.Cross(Vector3.forward, targetForward);
    var angle = Mathf.Acos(Vector3.Dot(Vector3.forward, targetForward)) * Mathf.Rad2Deg;

    spine.eulerAngles = rotAxis * angle;

What I am looking for now is if someone can point me what topic I should be looking in(because my poor maths skills are really getting me and I often use very poor workarounds for what could be solved easily with maths or physics), pseudo code to get me started or anything that might help me resolving this issue.

I know there are bunch of other ways to achieve what I am looking for and I have tried many of them like: using IK to position hands and then moving the guns up or down or having animations for each gun aiming up or down but honestly each method has it's own drawback(or its just me who is too noob for these things).

I followed this solution: Orienting a model to face a target

and many others, you might find it duplicate but none of the post on the internet has solved my problem(it is second day and I still can't figure this out).

Hope you understood the question and thanks for reading this:)


texts:
I am making a tower defense game in Flash and I have a slow tower that is built directly on the path. I have it setup to use a hitTestObject function.

The tower is in its own class and the enemies are in their own class.

In the update function for the tower, it has

if (this.hitTestObject(enemy))
{
    enemy.slow = true;
}

In the enemy class update function, I have:

if (slow == true)
{
    finalSpeed = speed/2;
}
else
{
    finalSpeed = speed;
}

This seems to work fine until I build a second slow tower. Whenever I build the second one, it works, but the  first one stops working (it no longer slows enemies). However, it is still detecting the collisions with the enemies. I don't understand why it doesn't slow them down though.


texts:
Can I use feature creep to my advantage?

Every time I prototype a game, features are inadvertently added. This happens either through coincidence, or it happens to be easy to add based on existing content.

If I know the genre of the game, can I just start making the basic mechanics and add features as they become apparent?

For example, if I want to make a 2d platformer over the course of 6 months, can I just start making the running, jumping, shooting, etc. and add the core mechanics as I inadvertently find them? Or is this too risky of a time investment without a predetermined plan?

My logic behind this is that the design will be more bang for the buck. The design choices will more easily be built around what is easy to make (time-wise).

In summary, is there anything wrong with building a game before I design it?


texts: OpenGL Drawing triangles at given world coordinates in modern opengl

texts:
It's my first time I am asking a question here so I apologize in advance for any mistake.
In the past two days, I decided to work on a 2D lighting system for my game and I came across a youtube channel that explained the ray casting algorithm (https://www.youtube.com/watch?v=fc3nnG2CG8U).
I've managed to implement the algorithm and now I have to fill the visibility polygon of the light by drawing triangles using the calculated intersection points (expressed in world coordinates).
I've tried two similar approaches:
Drawing using a dynamic vertex buffer
Calculate the normalized device coordinates with matrices multiplication (https://stackoverflow.com/questions/8491247/c-opengl-convert-world-coords-to-screen2d-coords) on the CPU and then upload the calculated vertex to a dynamic vertex buffer
Drawing using geometry shader
I did the same thing that I did in the previous approach but I transferred all the vertices calculation on the GPU side to increase the performance and used a geometry shader.
#version 420 core

layout (triangles) in;
layout (triangle_strip, max_vertices = 3) out;

uniform vec3 lightPos;
uniform vec3 v1Pos;
uniform vec3 v2Pos;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

void main()
{
    vec4 clipSpacePos = projectionMatrix * (viewMatrix * vec4(lightPos, 1.0f));
    gl_Position = vec4(clipSpacePos.xyz / clipSpacePos.w, 1.0f);
    EmitVertex();

    clipSpacePos = projectionMatrix * (viewMatrix * vec4(v1Pos, 1.0f));
    gl_Position = vec4(clipSpacePos.xyz / clipSpacePos.w, 1.0f);
    EmitVertex();

    clipSpacePos = projectionMatrix * (viewMatrix * vec4(v2Pos, 1.0f));
    gl_Position = vec4(clipSpacePos.xyz / clipSpacePos.w, 1.0f);
    EmitVertex();
}

Neither of them has worked.
Am I just using the wrong approach?


texts: Using unity Rigidbody 2D gravity, how to add to velocity?

texts:
I am creating a top-down game, and have an object I want to create a small bouncy illusion for. Since I dont have anything to collide with I'll have to do it with Scripts.

Without Unity I would probably do something like:

function fall ()
{
    this.vertical_speed = this.vertical_speed + GRAVITY;
    if (this.vertical_speed > TERMINAL_VELOCITY)
    {
        this.vertical_speed = TERMINAL_VELOCITY;
    }
    this.vertical_position = this.vertical_position - this.vertical_speed;
}

However in Unity we have the Rigidbody 2D, so I want to somehow use that for this.

if I set rigidBody.velocity = new Vector2(1, 0) * speed * delta;, it gets a constant speed, and ignores gravity. How can I add gravity?

i.e: I want to create a curve like:


texts: What are the differences between EGA and VGA for MSDOS API?

texts:
How different is the API for EGA and VGA for MSDOS applications? We're talking about the API that was used in games like Doom, Quest for Glory, Duke 3D, etc.

More specifically, how much work would be involved in changing an application's use of EGA APIs to VGA APIs? or SVGA even? They seem to be fairly similar in terms of interrupt strategies, registers used, etc. Looking for a little more definite answer though, if possible.

Forum post that suggests wrapping memory access may provide a partial solution:
http://www.allegro.cc/forums/thread/604334

Some basic information on using VGA, but nothing on EGA:

http://www.brackeen.com/vga/basics.html

http://www.wagemakers.be/english/doc/vga


texts:
HTML5 games have viewable source code. Is there a way to make them like swf file?

How to hide the game algorithm?

What do you think of the Firefox JavaScript Deobfuscator Plugin and obfuscation?


texts:
I have a set of seamless tiling textures. I want to be able to take an arbitrary model and create a UV map with these properties:

No stretching (all textures tile appropriately so there is no stretching and sheering of the texture)
The textures display on the correct axis relative to the model it's mapping to (if you look at the example, you can see some of the letters on the front are tilted, the y axis of the texture should be matching up with the y axis of the object. Some other faces have upside down letters too)
the texture is as continuous as possible on the surface of the model (if two faces are adjacent, the texture continues on the adjacent face where it left off)
the model is closed (all faces are completely enclosed by other faces)

A few notes. This mapping will occur before triangulation. I realize there are ways to do this by hand and it's probably a hard problem to automatically map textures in general, but since these textures are seamless and I just need uniform coverage it seems like an easier problem. I'm looking for an algorithmic approach to this that I can apply in general, not a tool that does it.

What approach would work for this, is there an existing one? (I assume so)


texts:
I use XNA for my projects and on those forums I sometimes see references to the fact that swapping an effect for a mesh has a relatively high cost, which surprises me as I thought to swap an effect was simply a case of copying the replacement shader program to the GPU along with appropriate parameters.

I wondered if someone could explain exactly what is costly about this process? And put, if possible, 'relatively' into context?

For example say I wanted to use a short shader to help with picking, I would:

Change the effect on every object, calculting a unique color to identify it and providing it to the shader.
Draw all the objects to a render target in memory.
Get the color from the target and use it to look up the selected object.

What portion of the total time taken to complete that process would be spent swapping the shaders?
My instincts would say that rendering the scene again, no matter how simple the shader, would be an order of magnitude slower than any other part of the process so why all the concern over effects?


texts: Most efficient language for rewriting a tile-based board game as a video game?

texts:
I've been working on a hex-based board game. Every time I make changes, especially changes that require redesigning the map, it takes a good chunk of time and money. It might be more efficient to write it as a video game, at least for designing it and showing off mock-ups. I've always wanted to learn a programming language anyways, so this gives me a good excuse.

Things that are important:

Hex grid movement, obviously
Hot-seat or online play - it's a multiplayer board game, thus a multiplayer video game
Keep track of what you might call "touchdowns" at a specific location, as well as HP and movement speed

AI would be unnecessary, so would sound effects or a matchmaking server. I just want to be able to show this to people.

Languages I've thought about learning before:

Flash, because it's ubiquitous
C seems to be an industry standard for video games
Javascript, because it seems to be the more powerful successor to flash
Python, because geeks always geek out about how awesome it is

If one of those languages would work well for my purposes, awesome! If there's a more efficient language to learn for this particular application though, I'm open to that.


texts: Game Maker (and others): what data type is colour and how can I compare them?

texts:
In Game Maker, and I imagine other engines, one can "make colour" by defining either the red-green-blue values of the colour or its hue-value-saturation.

I want to create a program that can compare how similar two given colours are, but without built-in functions that detects the "components" (red-value, saturation etc.) of colours, this is kind of hard.

So, I am asking what data type (compound? integer? real number?) is a colour represented in Game Maker and how I can compare them.


texts: How do you make a particle system collision add a force to an object towards the particle system?

texts:
I have a lightning particle that gets shot at the ground. I want the particles to collide with the object they hit and add an upward force. I tried just entering a negative force in the Collider Force tab but it defaults to 0. If anyone knows a way to do this it would be greatly appreciated!

Edit: I want to send the cube in the photo upwards by adding a force on its y-axis. The Particles should remain as they are.


texts:
I was wondering about the method called OnDestroy in Unity (4.5.2f1) on Windows 8.1 Update 1. I know garbage collection in C# in non-deterministic, so I was wondering if game objects had OnDestroy called the moment I called Destroy on them, or when the garbage collector was invoked?

If this is not the case, what are my alternatives? I could of course just call a method inside of the object to be destroyed just before I invoke destroy, but there may be a more elegant solution available that I don't know about.

Note: I did try checking this myself, but being non-deterministic I may not be able to rely on that behavior occurring every time.


texts:
I have often come across many websites which provide free/ paid PSD layouts of website UIs for use by web/ graphics developers.
Are there any such sites where one can find PSD layouts of UI kits for games?

Actually I am looking for some AAA quality game UI and menu screen kits - I have something like the ones in Crysis 2 and Crysis 3 in mind.


texts: dynamic 2d texture creation in unity from script

texts:
I'm coming from HTML5 and I'm used to having the 2D Canvas API I can use to generate textures. Is there anything similar in Unity3D?

For example, let's say at runtime I want to render a circle, put 3 initials in the middle and then take the result and put that in a texture. In HTML5 I'd do this

var initials = "GAT";
var textureWidth = 256;
var textureHeight = 256;

// create a canvas
var c = document.createElement("canvas");
c.width = textureWidth;
c.height = textureHeight;
var ctx = c.getContext("2d");

// Set the origin to the center of the canvas
ctx.translate(textureWidth / 2, textureHeight / 2);

// Draw a yellow circle
ctx.fillStyle = "rgb(255,255,0)"; // yellow
ctx.beginPath();
var radius = (Math.min(textureWidth, textureHeight) - 2) / 2;
ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
ctx.fill();

// Draw some black initials in the middle.
ctx.fillStyle = "rgb(0,0,0)";
ctx.font = "60pt Arial";
ctx.textAlign = "center";
ctx.fillText(initials, 0, 30);

// now I can make a texture from that
var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, c);
gl.generateMipmap(gl.TEXTURE_2D);

I know I can edit individual pixels in a Unity texture but is there any higher level API for drawing to texture in unity?