texts: P2P synchronization: can a player update fields of other players?

texts:
I know that synchronization is a huge topic, so I have minimized the problem to this example case.

Let's say, Alice and Bob are playing a P2P game, fighting against each other. If Alice hits Bob, how should I do the network component to make Bob's HP decrease?

I can think of two approaches:

Alice perform a Bob.HP--, then send Bob's reduced HP to Bob.
Alice send a "I just hit Bob" signal to Bob. Bob checks it, and reduce its own HP, then send his new HP to everyone including Alice.

I think the second approach is better because I don't think a player in a P2P game should be able to modify other players' private fields. Otherwise cheating would be too easy, right?

My philosophy is that in a P2P game especially, a player's attributes and all attributes of its belonging objects should only be updated by the player himself. However, I can't prove that this is right. Could someone give me some evidence? Thanks :)


texts: Trouble loading sprite from spritesheet with Phaser

texts:
I am working on re-creating a breakout clone to help me learn Phaser (following the overall design of jsbreakouts.org). Anyway, I have the start screen set up. From the start screen, I can transition to the game state without any problems. In my game state, I can load the background and the paddle without issues. The paddle responds to mouse input as it is supposed to.

But the ball does not load for some reason. The ball is coming from a spritesheet. Each ball in the sheet is 16x16 and there are 5 of them. I can't even get one of them to load, let alone animate them.

The balls spritesheet is in the same directory as the paddle. I have looked at other code online and as far as I can tell, I'm doing it right. Yet, it is not working.

What am I doing wrong?

Here's my game state code:

var paddle;
var ball;

var Game = {

preload : function() {
        // Here we load all the needed resources for the level.
        game.load.image('background', './assets/bg_prerendered.png');
        game.load.image('paddle',     './assets/paddle2.png');
        game.load.spritesheet('ballsheet', './assets/balls.png', 16, 16, 5);
        game.load.spritesheet('tiles', './assets/tile_spritesheet.png', 32, 16);
    },

create : function() {
    //enable physics
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.physics.arcade.checkCollision.down = false;

    //add the background
    background = game.add.sprite(0, 0, 'background');

    //add score text placeholder
    game.add.text(50, 390, "Lives: 3    Score: 700   Level: 1", { font: "12px sans-serif", fill: "#000000"});

    //add the paddle and set it up
    paddle = game.add.sprite(136, 384, 'paddle');

    //set the anchor to be the lower center of the paddle
    paddle.anchor.set(0.5,1);

    //enable paddle physics
    game.physics.enable(paddle, Phaser.Physics.Arcade);
    paddle.body.immovable = true;
    paddle.body.collideWorldBounds = true;

    ball = game.add.sprite(100,100, 'ballsheet');
    ball.frame = 0;
    //ball.animations.add('rotate',[0,1,2,3,4], 10, true);
    //game.physics.enable(ball, Phaser.Physics.Arcade);
    //ball.body.collideWorldBounds = true;
    //ball.play('rotate');

},
    update: function() {
        paddle.x = game.input.x;

    },
};


texts: Cocos2d-x project every time must compile the project plus other libraries

texts:
I'm using cocos2d-x v3.6 for win32 desktop and Visual Studio 2013 with c++.

When I change the code and then compile the project again, I must re-compile my project AND other libraries every time (e.g. libraries: libbox2d and libcocos2d), and this phase takes a long time.

I don't know why I get this bad behavior of having to re-compile the dependency libraries every time with the project.

Is there is any way to change this bad behavior, to compile the project only without dependency libraries every time?


texts: Is it considered poor programming to do this with xna components?

texts:
I created my own Menu System that is event driven.

In order to have a loading screen and multithreaded loading to work, I devised this sort of implementation:

//Let's check if the game is done loading.
if (_game != null)
{
    _gameLoaded = _game.DoneLoading;
}

//This means the game is loading still,
//therefore the loading screen should be active.
if (!_gameLoaded && _gameActive)
{
    _gameScreenList[2].UpdateMenu();
}

//The loading screen was selected.
if (_gameScreenList[2].CurrentState == GameScreen.State.Shown && !_gameActive)
{
     Components.Add(_game = new ParadoxGame(this));
     _game.Initialize(); //Initializes the Game so that the loading can begin.
     _gameActive = true;
}

In the XNA Game Component that contains the actual game, in the LoadContent method I simply created a new Thread that calls another method ThreadLoad that has all the actual loading.

I also have a boolean variable called DoneLoading in the XNA Game Component that is set to true at the end of the ThreadLoad.

I am wondering if this is a poor implementation.


texts:
I have a Health Bar in my Unity game and it's implemented as a GUITexture with gradient image from red to green.

Now I can reduce it's width from max width to 0, but is still scaled gradient.

public void UpdateHealthBar(int hitPoints) {
    healthBar.pixelInset = new Rect(
        healthBar.pixelInset.x, healthBar.pixelInset.y,
        3* hitPoints, healthBar.pixelInset.height);
}

But I want to hide (make transparent) the right part of this health bar in game progress.

How can I do this?
Thanks!


texts: How to apply effects that occur (or change) over time to characters in a game?

texts:
So assume that I have a system that applies Effects to Characters like so:

public class Character {
    private Collection<Effect> _effects;

    public void AddEffect (Effect e) {
        e.ApplyTo(this);
        _effects.Add(e);
    }
    public void RemoveEffect (Effect e) {
        e.RemoveFrom(this);
        _effects.Remove(e);
    }
}

public interface Effect {
    public void ApplyTo (Character character);
    public void RemoveFrom (Character character);
}

Example Effect: Armor Buff for 5 seconds.

void someFunction() {
    // Do Stuff ...
    Timer armorTimer = new Timer(5 seconds);
    ArmorBuff armorbuff = new ArmorBuff();
    character.AddEffect(armorBuff);
    armorTimer.Start();
    // Do more stuff ...
}

// Some where else in code
public void ArmorTimer_Complete() {
    character.RemoveEffect(armorBuff);
}

public class ArmorBuff implements Effect {
    public void applyTo(Character character) { character.changeArmor(20); }
    public void removeFrom(Character character) { character.changeArmor(-20); }
}

Ok, so this example would buff the Characters armor for 5 seconds.  Easy to get working.  But what about effects that change over the duration of the effect being applied.  Two examples come to mind:

Damage Over Time: 200 damage every second for 3 seconds.  I could mimic this by applying an Effect that lasts for 1 second and has a counter set to 3, then when it is removed it could deal 200 damage, clone itself, decrement the counter of the clone, and apply the clone to the character.  If it repeats this until the counter is 0, then you got a damage over time ability.

I'm not a huge fan of this approach, but it does describe the behavior exactly.

Degenerating Speed Boost: Gain a speed boost that degrades over 3 seconds until you return to your normal speed.  This is a bit harder.  I can basically do the same thing as above except having timers set to some portion of a second, such that they occur fast enough to give the appearance of degenerating smoothly over time (even though they are really just stepping down incrementally).

I feel like you could get away with only 12 steps over a second (maybe less, I would have to test it and see), but this doesn't seem very elegant to me.  The only other way to implement this effect would be to change the system so that the Character checks the _effects collection for effects that alter any of the properties any time that they are being used.  I could handle this in functions like getCurrentSpeed() and getCurrentArmor(), but you can imagine how much of a hassle it would be to have that kind of overhead every time you want to do a calculation with movement speed (which would be every time you move your character).

Is there a better way to deal with these kinds of effects or events?


texts: Why might a PC game have a set number of resolutions?

texts: There's an obvious reason games choose to use a set number of resolutions in fullscreen mode - a machine only has access to its own set of resolutions, and the intersection of the two sets determines what resolutions the game can run.  However, even in windowed mode the user is often limited to some set of resolutions.  What are some reasons games might opt to limit the size of the window in this way, rather than let the user dynamically resize the window themselves?


texts: Transforming normals along with vertex? (GLSL)

texts:
So, I got a model matrix (Via uniform variable) in the shader, is there any way to use the model matrix to transform the normal of a vertex that has been transformed with glm::transform/rotate?

If you want, here is the code:

VERTEX SHADER:

#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 Normal;
out vec3 fragmentColor;
out vec3 vertPos;
out vec2 UV;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = vertexPosition_modelspace;
    Normal = vertexNormal;
}

FRAGMENT SHADER:

#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec3 vertPos;
in vec2 UV;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;

void main(){
    vec3 lightPos = vec3(1, 1, 1);
    mat3 normalMatrix = transpose(inverse(mat3(Model))); // I think this line could do it, but it doesn't seem to work.
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos, 1));
    vec3 surfaceToLight = lightPos - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0.2, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));

}


texts: Find point along x axis where yz plane flips to back facing after perspective projection. Have a solution but don't know why it works

texts:
I am trying to find the point along the x axis where a plane with normal pointing along the x axis would flip to back facing after perspective projection. Essentially the red line in this image.
My first attempt to find it I just sampled along the x axis checking if a triangle there was back facing after projection. This only gave me an approximation but I could make the approximation as accurate as I wanted by just sampling more planes so I used this as a baseline to verify other solutions.
I then tried the following:
vec4 center = projection.inverse()*vec4(0,0,0,1);
center /= center.w;
float d = dot(center.xyz, vec3(1,0,0));
vec3 point = vec3(1,0,0)*d;

But this did not work, it was close but not right. See this image, the red line is the sampled point and the blue is the one calculated from that.
I then tried changing the calculation for center to projection.inverse()*vec4(0,0,-1,1) to see what that would look like. With the the sampled point in red, the blue line being the previous version and the green the new version. I got the following image which as you can see is still not correct.
But I noticed that the green was always directly between the blue and the red so I tried the following.
vec4 c1 = projection.inverse()*vec4(0,0,0,1);
c1 /= c1.w;
float d1 = dot(c1.xyz, vec3(1,0,0));
vec4 c2 = projection.inverse()*vec4(0,0,-1,1);
c2 /= c2.w;
float d2 = dot(c2.xyz, vec3(1,0,0));
float d = (d2-d1)*2 + d1;
vec3 point = vec3(1,0,0)*d;

Which seems to be correct but I have no idea why that works. It is always extremely close to the sampled point so I assume it is correct.
My question is why does this work?


texts: How to make a character that moves like a slinky?

texts:
I have a school assignment to make a 2D platformer game, with a character that moves like a slinky:

(Animated example from the assignment linked above)

At first, the character needs to grow in height over time
When the player presses a button, the character starts to bend toward the next platform
Its height when you press the button determines whether it will hit the next platform
After that it must shrink to its initial size, and it goes over again.

How can I approach this?


texts: Is it better to cut and store all sprites needed from a spritesheet in memory, or cut them out just-in-time?

texts:
I'm not sure what's best practice here as I have little experience with this. Essentially what I am asking is...

if it's better to get your single PNG with all your different sprites on it for use in-game, cut out every sprite on startup and store them in memory, then access the already-cut-out sprite from memory quickly

or

Only have the single PNG with all the different sprites residing in memory, and when you need, for example, a tree. You cut out the tree from the PNG and then continue to use it as normal.

I imagine the former is more CPU friendly than the latter but less memory friendly, vice versa for the latter. I want to know what the norm is for game dev. This is a pixel based game using 2D art. Each PNG is actually an avatar's sprite sheet with each body part separated and then later joined to form the full body of the avatar.


texts: How can I change the parents rotation so the childs rotation is looking at a specific direction

texts:
I have a child object which is always having different positions and rotations (thats my VR Headsets Eye-Gameobject)
I cannot modify the position and rotation of that.

I want to set my view to a certain "startposition" and "startrotation" so the player always has the same view at the start of the game.

The childs local position is always set to some values.
So I cannot unparent it.
If I unparent it, I change his position.

now..

It works with the position.

Parent.transform.position =  2 * ParentStartPostion - Eye.localPosition;

^
This line of code here sets my parent object so that my Gameobject: "eye-camera" is where i want it to be.

For the rotation part, i would do following:

Eye.parent = null; //unparent the eye to the world
Parent.transform.position = Eye.position; //set my Parent to the same position as Eye
Eye.parent = transform; //parent it back. Local Eye should be 0.0.0 now.
Parent.transform.rotation = Quaternion.LookRotation(StartForward, StartUp); // i can rotate the at the direction I want it.

But after I unparent my Eye the position of the local(which is also global) is set to a different value.
And after I parent it back, its set to the old value again.

Eye.parent = null; //unparent my eye to the world - Eye moves anyway because its movend by SteamVR
Parent.transform.position = Eye.position; //set my Parent to the same position as Eye (works)
Eye.parent = transform; //parent it back. Local Eye moves back where it was and there is a distance between parent and eye again.
Parent.transform.rotation = Quaternion.LookRotation(StartForward, StartUp); // the rotation changing my eyes position because its parented. Also the rotation is wrong.

And now i dont know anymore how to solve this problem.

so... i painted my problem in paint for better understanding:


texts:
As a hobbyist junior game programmer, I have done multiple small OpenGL projects just to have fun with 3D. I've tested VBOs in C++ and in Java and I found something or rather understood Java tutorials differently than the C++ ones. When using the glVertexAttribPointer function in Java, it is told that the parameter stride (second from the end) is the size of an entire vertex.

void glVertexAttribPointer( GLuint index,
                            GLint size,
                            GLenum type,
                            GLboolean normalized,
                            GLsizei stride,
                            const GLvoid * pointer);

Considering the following my interpretation of the Java/OpenGL tutorial, this is what should be done (as example) in C++:

glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(0));
glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(sizeof(float)*3));
glVertexAttribPointer(texCoord0Loc, 2, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(sizeof(float)*6));

struct MyVertex
{
    float x, y, z;
    float nx, ny, nz;
    float s0, t0;
};

Now I'm really confused because this works in my Java code. However, in my old C++ code, I was something like this:

glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex) - sizeof(aPosition), BUFFER_OFFSET(0));
glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex) - sizeof(aNormal), BUFFER_OFFSET(sizeof(float)*3));
glVertexAttribPointer(texCoord0Loc, 2, GL_FLOAT, GL_FALSE, sizeof(MyVertex) - sizeof(aTextCoord), BUFFER_OFFSET(sizeof(float)*6));

My question is: should the stride parameter be the size of an entire vertex in bytes or should it be the number of bytes separating another vertex attribute of the same type, i.e. the size between two normals, positions, texture coordinates, ect?


texts: Get quaternion between two objects on sphere

texts:
In a planetary gravity environment objects are represented in the following way:

struct object {
    struct quaternion quat; // quaternion to represent the rotation between the object and the center of the planet
    float dist; // distance from the center of the planet
};

Here are the steps at which I position my player:

// start at center of the planet
applyQuaternion(&object.quat);
glTranslatef(0.0f, object.dist, 0.0f);
drawObject(&object);

Step 1, translate to center of planet:

Step 2, apply quaternion:

Step 3, translate outwards by distance value:

I am also able to get the current position of the player or enemy by using this code:

struct matrix initialMatrix, resultantMatrix;
glPushMatrix();
getPositionMatrix(&initialMatrix);
applyQuaternion(&player.quat);
glTranslatef32(0, player.dist, 0);
getPositionMatrix(&resultantMatrix);
playerPosition = matrixTranslationToVector(initialMatrix, resultantMatrix);
glPopMatrix();

Given two objects:

struct object player;
struct object enemy;

How can I get the enemy to face in the direction of the player, whilst always standing upright on the planet, using quaternions?

I want the enemy to go from this:

To this:

His feet always on the planet, and head always away from planet.

I'm able to rotate on the axis which doesn't affect the position (from first enemy diagram to second enemy diagram like so):

// Rotate right
Quaternion_multiply(&player.quat, Quaternion_fromAxisAngle(vect(0.0f, 0.0f, 1.0f), degreesToAngle(2)));

// Rotate left
Quaternion_multiply(&player.quat, Quaternion_fromAxisAngle(vect(0.0f, 0.0f, 1.0f), degreesToAngle(-2)));

So I'm unsure as to why I'd need a local orientation in addition to the quaternion I already have.


texts: How can I make the "Strength" attribute more attractive to Wizard/Caster classes in a RPG game?

texts:
I have a game where, among many attributes, is Strength and Constitution.
In Ultima Online, Strength was used for hit points. However, I would like to avoid this- as Hit Points are so incredibly important, every class will want to have a lot of them in any game you play. In almost all MMORPG's and in many RPG's, players stack constitution almost as much as their primary attribute.

I have a plethora of ways in which INTELLIGENCE helps a WARRIOR type. It is the problem of the attribute STRENGTH helping a WIZARD type that is giving me so much difficulty.

Strength can more easily be an important statistic for Warrior and Rogue types, as they are both melee damage- and players tend to love stacking high damage. However, Strength is all but useless to a Wizard who casts spells from afar, and relies on Intelligence as their damage attribute.

What can I do to strength, to make it more appealing to wizard types, or any class that does not perform any melee combat?

Correct me if I am wrong, but I do not feel as though Spells/Magic should be more powerful because someone has more physical muscles and capacity to lift more. It makes sense to give Magic more power if the caster had a lot of fortitude or a overall healthy body, but that is already defined as Constitution.

I want to make Strength as attractive as Intelligence, to Wizard types than in stereotypical RPG's.

I was able to find balance between a "Dumb Brute Warrior" vs "Intelligent Warrior".
How can I find a balance between a "Buff Conan Wizard" vs "Intelligent but Frail Wizard" without introducing melee combat?

Adding unique gameplay features or altering the traditional RPG style of play is more than welcome.


texts: Creating a player that can hold different items

texts:
I am making a game using Java, LibGDX and Box2D. What would be the best way to create a player that can hold:

no item
one item from group A
one item from group B
one item from both groups

Items from group A can only be used to attack, and are held in the right hand.
Items from group B can only be used to defend, and are held in the left hand.

Should I add the item to the player class and render/update the item in the player class? Or is there any best way to this that I am not aware?

This is the best way I know how to do it:

I would also be interested in any design pattern that could be applied to this situation.


texts: What NPC gets attacked first when attacking an NPC party in an RPG?

texts: Let's say I am in a battle with four trolls, and I have the highest initiative, so I attack first. Should I randomly choose a troll to attack? Proximity to each troll does not matter (it is not a factor in the algorithm). I remember playing an older RPG (I think one of the Final Fantasy games on N64), and the attacks appeared random. You might have one troll that never gets hit, or you might have one that always gets hit. Is there an acceptable standard?


texts: How can I implement 2D cel shading in XNA?

texts:
So I was just wondering on how to give a scene I am rendering a hand drawn look (like say Crayon Physics). I don't really want to preprocess the sprites and was thinking of using a shader. Cel shading supplies the effect I want to achieve, but I am only aware of the 3D instances for it.

So I wanted to ask if anyone knew a way to get this effect in 2D, or if cel shading would work just as fine on 2D scenes?

Edit:The reason why i didn't want to do preprocessing ,was that i almost don't have anything to prepossess.I have some material textures ,which are basically just black and white images and using them i create textures from specific vertices ,which represent entities in the game (mostly physics based ones).So i wasn't sure how to processes the textures for the texture mapping to work as i intended.Thanks for the help!


texts:
I've started trying a few things with Sprite Kit for Game Development. I was creating a brick breaking game. So I've run into a issue on how to randomize the initial starting direction of the ball.

I set the following properties for my ball which launches from the paddle.

ball.physicsBody.friction = 0;
ball.physicsBody.linearDamping = 0;
ball.physicsBody.restitution = 1 ; //energy lost on impact or bounciness

To start at different direction during the gameplay, I've randomized the selection of the 4 vectors because I'm using the applyImpulse method to direct the ball in a particular direction and I need to make sure the ball does not go slow if the vector values are low.

int initialDirection = arc4random()%10;
CGVector myVector;

if(initialDirection < 2)
{
    myVector = CGVectorMake(4, 7);
}
else if(initialDirection >3 && initialDirection <= 6)
{
    myVector = CGVectorMake(-7, -5);
}
else if(initialDirection >6 && initialDirection <= 8)
{
     myVector = CGVectorMake(-5, -8);
}
else
{
     myVector = CGVectorMake(8, 5);
}
//apply the vector
[ball.physicsBody applyImpulse:myVector];

Is there any way I can randomize the direction and still maintain a speed for my ball ?


texts: Why does my isometric rendering technique leave large gaps between tiles?

texts:
I've followed tutorial after tutorial for converting from cartesian coordinates to isometric coordinates.

The cartesian behavior of my game works fine... that part is easy... For the most part, I can even get the isometric display to work, following along with the math I've found online. But it comes with some serious problems.

I use the following formulas in the getIso() functions:

isoX = (X-Y) - xOrientation
isoY = ((X+Y)/2) - yOrientation

I also apply the following transformation and draw each terrain square with its filter:

double axis = (double) GameWorld.GRID_SIZE;
transform.scale(1, 0.5);
transform.rotate(Math.toRadians(-45), axis, axis/2);
op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);

It comes out looking like this when the terrain is drawn:

Each block should be neatly side-by-side. If I change the scale values (while maintaining the 2:1 ratio) then either the terrain image is clipped or they start to overlap one another, but it's never perfectly aligned. Here's the function I use to draw the terrain:

void draw(Graphics2D G)
{
    int x = world.getIsoX(xCoord, yCoord);
    int y = world.getIsoY(xCoord, yCoord);
    if (isVisible() == true) G.drawImage(op.filter(sprite.buffer, null), x, y, null);
}


texts: Why do I get these "Invalid command android" errors trying to build for Android in Unity?

texts:
Trying to move a unity project over to android using gradle as the build system. I get the following 3 errors:

Error:Invalid command android

CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir="/Users/joeljohnson/Library/Android/sdk/tools" -Dfile.encoding=UTF8 -jar "/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

and

Error building Player: CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir="/Users/joeljohnson/Library/Android/sdk/tools" -Dfile.encoding=UTF8 -jar "/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]

It turns out a lot of people have been having this problem and the most common solution is to move to an earlier version of the apk. When I tried that, I still received the same three errors. I moved down to api level 23 from the most current. I am one a mac.
    exit code: 64


texts:
I would like to plot a small globe where the main character can walk, exactly like Sonic & Knukles Bonus Stage. For those who won't google it, here is a picture.
I am familiar with Raycasting, used in Wolfenstein and other games to "simulate" a 3D perspective in a 2D map.
But I could not figure how to program the globe thing, and I suppose that it was not a real 3D rendering, as Sonic was a 16 bit game.
Any idea on how to do it without any sofisticated 3D engine?


texts:
I wish to address the low re-usability of game technology (at least provide a theoretical solution).

I'm considering an approach using a semantic game format, effectively decoupling the story and logic of games from its presentation and art. I can see a few immediate advantages:

Completely platform independent games (think SCUMM games)
Optionally: presentation independent games (cheaper and more flexible)
Game editors can provide different specialized game construction UI's, but producing the same game format. (think bytecode)
Game engine technology (voice synthesis, facial synthesis, skeleton animation etc. etc.) can be reused across games as a part of (or extensions to) the semantic game format/language.
Game art and game technology can be licensed extensions, paid by game distributors, independent of client platforms.

Apart from the huge resources needed to establish such a game format/language, are there any theoretical limitations that should stop this concept?


texts: Rendering Performance: num Draw Calls == num Texture Bindings

texts:
I'm making a game with Libgdx 1.6.4 and experience some lag issues on iPhone 4 and then discovered:

// in the constructor
GLProfiler.enable();

...

// in the render method
Gdx.app.debug("draw calls: " + GLProfiler.drawCalls);
Gdx.app.debug("texture bindings: " + GLProfiler.textureBindings);
GLProfiler.reset();

What the log shows is that the number of draw calls is always equal to the number of texture bindings. Do you know if this is ok?

It seems strange because I have all images as TextureRegion in only one TextureAtlas with size 1024x512. Isn't it supposed to be that I will have for example 50 draw calls and only 1-2 texture binding instead of 50 draw calls and 50 texture bindings. Can this be the source of the lag?

Another clue may be, that I use a SpriteBatch and Scene2d Stage at the same time, but they both use the same TextureAtlas. The Scene2d Skin is loading the TextureAtlas and SpriteBatch draws TextureRegions from the skins' regions.

Thank you for any help.

--- Update ---

The main SpriteBatch (it's only one) is making 9 totalRenderCalls. The value of maxSpritesInBatch is 26. These values seem normal from what I read in the Docs and the FPS during rendering with the SpriteBatch is 60 FPS. Which is ok, no problem there.

The problem with the lag is when I use a Scene2D Stage to display a Dialog above the GameScreen. The Stage has it's own batch which I don't manipulate directly. When the Dialog is displayed the frame rate drops to 49-50 and the Animations in the Dialog are crappy. I guess the problem has something to do with Texture Binding of the main SpriteBatch and the Stage's SpriteBatch.


texts:
I am trying to access a texture in a fragment shader to overlay this texture over a certain area.

varying vec4 v_color;
varying vec2 v_texCoord0;

uniform sampler2D u_sampler2D;
uniform vec4 u_oldcolor;
uniform vec4 u_newcolor;
uniform vec3 u_noise;

void main(){

    vec4 color = texture2D( u_sampler2D , v_texCoord0 ) ;
    float threshold = 0.005f;
    if(color.r <= (u_oldcolor.r + threshold) && color.g <= (u_oldcolor.g + threshold) && color.b <= (u_oldcolor.b + threshold)
    && color.r >= (u_oldcolor.r - threshold) && color.g >= (u_oldcolor.g - threshold) && color.b >= (u_oldcolor.b - threshold)){
        color.rgb = u_newcolor.rgb + vec3(v_texCoord0, 0.1);
    }

    gl_FragColor = color ;

}

For every pixel the shader checks for a certain color and replaces it with a new color+v_texCoord0.

Now I am want to bring in a third component: a noise texture to make it look like this:

I searched the web for a solution but I could not find anything helpful.

My questions:
1.Is this even possible to accomplish via a shader?
2.How to access the texture ?

I hope that my questions are clear and proper for this forum :) .


texts:
I need to get access project's gravity value which set in Project Settings -> Physics -> 3D -> Gravity, however I couldn't find any related information about this.

How do I get project's gravity value in GDScript? In Unity, it can be done by simply Physics.gravity, but in Godot, couldn't find similar.

Using Godot 3.1.1


texts: Camera will not move between given points, stuck at first given point

texts:
[EDIT: Working code added]

[Original question]

I'm putting together a "raid cam" or "overview cam" for a given map in my shooter for an observing player to use to fly down a given preset path (to prevent griefing and cheating, this may change in my final build)

Unfortunately though I can get the program to invoke the given method, iterate through each of my points, and display this to the debug console, my player camera does not move from the very first start point. I'm attempting to use the Vector3.MoveTowards function at the moment but if there is a better way to move the camera between the points I am open to that.

[/Original question]

The code is as follows, and heavily commented for clarity on my thought process:

// Invoked from external function, takes precoded path and translates player between the given points
public void FlyThroughPath(List<Vector3> path){

    // If the flightpath is not empty
    if(path.Count > 0){
        // If we haven't already enabled fly through mode
        if (!enabled){
            Debug.Log ("enabling fly through mode");
            // Enable fly mode
            enabled = true;
            // Assign our starting point
            CurrentIndex = 0;
            StartPoint = path[0];
            // Move us to the start point
            transform.position = StartPoint;
        }else if (enabled && CurrentIndex < path.Count){
            Debug.Log ("Already enabled, moving to next point");
            // If the distance between the points is too far we keep moving towards that point
            if(Vector3.Distance(transform.position, path[CurrentIndex]) > 5.5f){
                Debug.Log("Too far keep moving");
                FlyToNextPoint(transform.position, path[CurrentIndex]);
            }else if (Vector3.Distance(transform.position, path[CurrentIndex]) <= 5.5f){
                Debug.Log ("Point reached move to next one");
                CurrentIndex++;
            }else{
                Debug.Log ("Ifs were too specific, whoops");
            }
        }else if(enabled && CurrentIndex >= path.Count){ // If enabled and we don't have another point in our path
            Debug.Log ("no more points let's disable the flythrough");
            // We have arrived at our last point so let's disable the flythrough;
            enabled = false;
        }
    }
}

// Takes two points and transforms the player camera between them at a preset speed
public void FlyToNextPoint(Vector3 start, Vector3 end){
    // Grab the time for movement speed and duration
    // Snag the player's last chosen speed for consistency
    m_speed = flyMotor.m_actualSpeed;
    // put together the time we want to use between the two points
    float t = m_speed * Time.deltaTime;
    // Move the player between the given points at the given speed
    Debug.Log ("Flying to " + end.ToString() + " from position " + start.ToString());
    // Move the player camera towards the next point from the given start point
    transform.position = Vector3.MoveTowards(start,end, t);
}

EDIT: For clarity the function is evoked here:

// Update is called once per frame
void Update () {
   [...]
   else if(cInput.GetKeyUp("Fly Mode Start")){
        Debug.Log ("Flythrough initiated in FlyMotor");
        // Instantiate and start the flight path functions
        AutoFlyThrough = GetComponent<FlyThrough>();
        AutoFlyThrough.FlyThroughPath(FlightPath);
    }

    if(AutoFlyThrough != null){
        if (AutoFlyThrough.enabled){
            // Check the position and continue to move the player
            AutoFlyThrough.FlyThroughPath(FlightPath);
        }
    }
}


texts: How to process multiple shadow maps in deferred shading

texts:
I'm attempting to implement shadow mapping in an OpenGL deferred shading system.

I know how to handle a single shadow map in the lighting stage, but I want my rendering system to be able to support multiple shadow maps.

At present, My lighting shader is capable of supporting up to 128 point and spotlights in a single pass.

I'd like to know how to modify the shader to handle an indeterminate number of shadow maps of each type (ortho for directional, cube for pointlights, projection for spotlights).

Normally, when I define a sampler in GLSL, i simply use :

uniform sampler2D shadowMap;

But I think it would be cumbersome to define up to 256 individual sampler uniforms, if it were even possible (which I am far from convinced about).

Is there a way to define an array of samplers which I can iterate through on a 1:1 ratio for each light, and if so, how would I do this?

For instance, I know that I can use UBO's to send the data for many lights to the shader, so can I do the same to populate an array of samplers, like so:

shadowMaps[MAX_SHADOWMAPS];

Or:

uniform sampler2D
{
    shadowMaps[MAX_SHADOWMAPS];
};


texts:
I am having trouble trying to think of how I am going to approach collisions in my game. My idea which sucked in the beginning because it would reduce performance dramatically has failed which was when I was updating the list of walls it would check collision with players but the player would just stop and wouldn't be able to move anymore. Collision not only has to work with player but with at least 15-20 other entities in the game as well. Does anyone have a good idea to check collision with a top down shooter?

Here is my update method with everything being updated:

public void update(float dt){

    inputHandler();

    //Update the player
    player.update(joystick1, joystick2, projectiles, dt);
    updateCamera();

    //Update them zombies
    for(int i = 0; i < enemies.size(); i++){
        Enemy e = enemies.get(i);
        e.update(player, dt);
        if(e.getDistanceFromPlayer() < 60){
            //check collision
            if(e.collided(player)){
                player.hit(e, particles);
            }
        }
    }

    //Update Projectiles
    for(int i = 0; i < projectiles.size(); i++){
        Projectile p = projectiles.get(i);
        p.update(dt);
        //Check if projectile has hit any enemies
        for(int j = 0; j < enemies.size(); j++){
            Enemy e = enemies.get(j);
            if(p.collided(e)){
                p.remove();
                e.hit(p);
                ParticleEmitter.createBloodParticle(particles, e.getX(), e.getY(), 5, 500, 10);
            }
        }
    }

    //Update Items
    for(int i = 0; i < items.size(); i++){
        Item item = items.get(i);
        if(item.collide(player)){
            if(item instanceof Ammo){
                player.getCurrentGun().addAmmo(item.getAmount());
            }
            if(item instanceof Health){
                player.addHealth(item.getAmount());
                if(player.getHealth() >= 100){
                    player.setHealth(100);
                }
            }
            item.remove();
        }
    }

    //Update them particles
    for(int i = 0; i < particles.size(); i++){
        Particle p = particles.get(i);
        p.update(dt);

    }

    int numberOfObjectInGame = 1 + walls.size() + enemies.size() + items.size() + particles.size() + projectiles.size();
    System.out.println(numberOfObjectInGame);

    logger.log();

}

I don't know when to check for collisions. Should it be done in the update method or in the player update method, or at some other point? Really confused at this point.

EDIT:

Ok so added 4 rectangle bounds to my player and had each one checked to see if they have collided with a wall. So right now it is working but i'm pretty sure this is horribly inefficient. Any way to make this more efficient...

Here is the code:

for(int i = 0; i < walls.size(); i++){
        Wall w = walls.get(i);
        if(Intersector.overlaps(w.getBounds(), up)){
            if(velocity.y < 0){
                velocity.y = 0;
            }
        }
        if(Intersector.overlaps(w.getBounds(), down)){
            if(velocity.y > 0){
                velocity.y = 0;
            }
        }
        if(Intersector.overlaps(w.getBounds(), left)){
            if(velocity.x < 0){
                velocity.x = 0;
            }
        }
        if(Intersector.overlaps(w.getBounds(), right)){
            if(velocity.x > 0){
                velocity.x = 0;
            }
        }
    }

It is checked to see if the player is colliding with every wall and the problem is this is only the player. This has to check with every moving entity in the game. Is this a good way to implement this into a game or should I look into something else?


texts: Does 64-bit translation and transformation slow down the engine significantly?

texts:
So, how does one go with rendering world space calculated in 64-bit? How can that even work? GPUs can use Double Precision, but significantly slower than FP32.
How can one achieve world space coordinates using 64-bits and then render it on consumer GPUs?

e.g.: Star Citizen and No Man's Sky claim 64-bit world coordinates.


texts: Can't scale properly to android device in Game Maker Studio 1.4

texts:
My phone is using a resolution of 360 x 640 with a 9:16 aspect ratio. I set my room in game maker to 360 x 640  and game maker thinks it's in landscape mode. I disabled landscape mode in the android settings and set to portrait only, like it should be. How do I get it to scale properly?

This is the code I have in my Scale Manager Object.

Create Event:

///Display Properties
ideal_width = 0;
ideal_height = 640;

aspect_ratio = display_get_width()/display_get_height();
ideal_width = round(ideal_height/aspect_ratio);

//check for odd numbers
if(ideal_width & 1) {
    ideal_width++;
}

for (var i = 1; i <= room_last; i++) {
    if(room_exists(i)) {
        room_set_view(i,0,true,0,0,ideal_width,ideal_height,0,0,ideal_width,ideal_height,0,0,0,0,-1);
        room_set_view_enabled(i,true);
    }
}

surface_resize(application_surface,ideal_width , ideal_height);
window_set_size(ideal_width,ideal_height);
room_goto(room_next(room));


texts:
Who has the rights to the party game Mafia / Werewolf?

Or is it public domain, meaning anyone can do an implementation of the game and release it as a commercial product?

Update 1:
According to this question:
Making a mobile app from a board game. Copyright infringement?

You can't copyright concepts or mechanics. This basically means this should be public domain, right?


texts: SAT collision detection and stacking objects

texts:
I'm working on a small game for Android which deals with some simple physics, including the need to stack objects on top of one another without jitter. This infamous "stacking collisions" issue with custom collision/physics engines really has me on the ropes with this project.

To highlight the issue I'm gonna go through a basic rundown of my gameloop and the order in which this engine computes the various steps. For example, lets say we have 3 objects in this scene. 2 boxes and a ground floor. The update loop is as follows:

Apply external and internal forces to each object (including gravity, any movement from input, etc.).
Use a collision tree to separate the various game objects into potential collision pairs (this is working just fine).
Run a collision detection algorithm on each pair to get a contact manifold for each collision that occurs this frame. My project is using SAT and its been working very well.
Sort the list of contact manifolds to order collisions by time of occurance.
Loop through the ordered manifolds and solve each collision as necessary.
Update each object's position in the world with the results of the collision correction and render.

When dealing with one pair of objects in isolation, this works great. But when you add a 3rd object to the simulation and stack them on top of each other the resulting simultaneous collisions result in visible jitter as the objects are pushed in and out of each other due to the many manifolds they have to deal with.
In my example the static ground remains stationary but the bottom box jitters in and out of the ground slightly as the top box pushes down on it due to gravity. Adding an iteration loop around steps 3, 4 and 5 helps stabilize the objects since they rerun the collision checks and get more accurate values, but to make the collisions perfectly stable I need a very high number of iterations (exponential amounts the larger the stack of objects), which kills the framerate of the game.

I'm not looking for any complete code, but some theories on how this stacking issue should be avoided would be fantastic. I'm just unsure where to take this logic-wise anymore, but I feel like anyone taking the custom physics engine route has probably seen similar issues.


texts: I want to make a moddable game. How does this affect my programming language choice?

texts:
I have been getting started making some small games in Java, and I am considering learning C# for a bigger project. I would very much like to make a moddable game, but someone told me that I need to stick with Java if I want the game to be moddable, though I don't understand why.

So, what programming language characteristics make a language more suited to moddable games?


texts: How can I add an animation curve to an object with no animations?

texts:
I want to scale text in different ways over time. I figured the best way to do this would be an animation curve. It turns out I need an actual animation clip just to create this curve.

My question is, is there a way to create and use an animation curve, or something like it, without making a redundant animation for this object? If not, is there anyway to create empty animation clips from the Unity editor?

Importing empty animations from third party applications into Unity just to use the animation curves seems ridiculous.


texts: Can i use Soccer/football team names in my web, iphone and android apps?

texts:
If i don't use logos, player names, sponsors or any images can i use team names in a for profit app? The reason i mention these is that i have seen countless references to images and badges but not the name in text format only.

Eg print the league table or show a fixtures list or show some user stats in relation to a team name in the app.

I read that a court has ruled in 2012 that fixture lists are not copyright-able as they involve pure scheduling logic and no artistic or innovative value. Also i know that logos, shield, images, player names and images etc are copyright-able.

Do team names fall under fair use if it is purely the team name in a fixture list or in a list or teams?


texts: Is there a way to identify, within a shader, the current GPU thread ID?

texts:
My question is rather simple: within a shader, is there a way (that works both in DirectX and OpenGL) to retrieve the ID of the given GPU thread being executed at the given iteration?

I am using Unity 5.3.4, if that helps. But I guess this is actually quite a platform-agnostic question. I have searched quite a bit for it, but found nothing satisfactory.


texts:
I have a UV-mapped model that I am about to animate and load into my game. Like most unwrapped models, I have several UV seams. In order to render the model correctly, I split each vertex along the seam into two vertices whose positions and normals are the same but whose UV coordinates differ. I do the same thing when I have more than one normal associated with a vertex.

This works fine for static models, but now I'm getting into the realm of animation. Technically since the two seam vertices occupy the same position in space they should use the same joint weights and joint IDs. Right now the simple way to do this is to just give them the same joint weights and joint IDs and then skin them separately. But to me this seems very wasteful because there are so many vertices along seams and so there will be many duplicate computations. It gets even worse since I need to render the animated model into the shadow map too.

Does anyone have any thoughts about improving this process? I've considered using something involving OpenGL transform feedback to save the results of the transformed vertices. This would at least help with computing transformed positions once and using the same results in the main render pass and shadow pass, but I still can't think of an elegant way to handle the duplicate computation along UV seams.


texts: glDrawArrays: Erasing the buffer between calls?

texts:
I have two VBOs, assigned to names 1 and 2. Only 2 is being drawn. However, if I comment out VBO 2, VBO 1 is drawn with no problem. Here's the relevant code.

                for m in shader._models:
                    try:
                        # Set the model's transform matrix uniform
                        vbo, mode = m.render_data
                        glUniformMatrix4fv(
                            shader.uniforms['model'][0],
                            1,
                            GL_FALSE,
                            np.array(m.model_matrix))
                        vbo.bind()  # Binds the VBO.
                        glDrawArrays(mode, 0, len(vbo))
                    finally:
                        vbo.unbind() # Unbinds it.

glGetting GL_ARRAY_BUFFER_BINDING in the loop gives me alternating 1 and 2s, so the buffers are binding correctly. The second object is smaller and positioned in a different location, so they aren't hiding each other.

The only explanation I can think of is glDrawArrays clears the whole buffer every time it draws? What the heck?


texts: Better way to find all sprites that would overlap with other sprite

texts:
first question on this site :-)

I'm not really sure that the title is very clear so feel free to edit/suggest a better one.

I have a piece of Game Maker code which works, but feels like a bit of a hack and also causes some side affects else where so I wanted to know if there is a better way.

I'm building a Tetris clone and this snippet occurs in the Step event of the falling tile parent object.  The idea is that when the falling object collides with something it should be replaced by 'brick' objects so that I can destroy them independently.

So what I want to do is test whether a brick would overlap with the falling object and if so then create a brick there.  I'm using an instance of brick (called trialBrick and created globally) to do the testing.

I could just try creating a brick and then destroy it if it doesn't overlap with the falling object but I'm not sure whether this is efficient or not.

Thoughts?

// just move the brick downward if we can by one pixel.
var obstacle = instance_place(x, y + 1, all);
if (obstacle != noone)
{
    isFalling = false;

    // loop through each row of the object.
    var row;
    var column ;
    for (row = y - 4 * brickSize; row < y + 4 * brickSize; row += brickSize)
    {
        for (column = x - 4 * brickSize; column < x + 4 * brickSize; column += brickSize)
        {
            // need to check whether the current row and column intersects with this falling object.
            trialBrick.x = column;
            trialBrick.y = row;

            with (trialBrick)
            {
                if (place_meeting(x, y, objFallingParent))
                {
                    instance_create(x, y, objBrick);
                }
            }
        }
    }
    trialBrick.x = 0;
    trialBrick.y = 0;

    // remove ourselves from the game.
    instance_destroy();
}

Edit:
The 'problem' is when I test whether the bricks are outside the play area (indicating game end) I have to remember to exclude the trialBrick.  It would be nicer if I didn't have the trialBrick at all.


texts: Box2D fixed timestep updating is twitchy on constant FPS

texts:
I'm messing around with libgdx and box2d and I'm trying to implement sidescroller movement with fixed timestep logic according to the famous Fix Your Timestep! tutorial/guide. However, logic updating seems to be twitchy and I'm not exactly sure why.

Here's the render method where the issue lies:

public void render() {
    handleCameraInput();
    handleTestBodyInputImpulse();
  //handleTestBodyInputVelocity();

    accumulator += Math.min(Gdx.graphics.getDeltaTime(), STEP);

    int logicStepCount = 0;
    while (accumulator >= STEP) {
        world.step(STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
        accumulator -= STEP;
        ++logicStepCount;
    }

    Gdx.graphics.setTitle("FPS: " + Gdx.graphics.getFramesPerSecond() + ", Logic steps: " + logicStepCount + ", Test body vel: " + testBody.getLinearVelocity());

    cam.update(); // update box2d world camera
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    renderer.render(world, cam.combined); // renders box2d bodies
}

From what I've noticed the logic while loop responsible for updating the physics sometimes doesn't execute (counter goes from 1 to 0 for one frame) and that seems to be causing the twitching. This is weird to me since delta time added to the accumulator is clamped and since the FPS is constant 60 on my machine I'd assume that the loop should always execute once. Am I doing something wrong? Is this behavior normal and is it something I am supposed to solve during rendering with interpolation?

Complete minimal example can be found here on Gist and can be run on any LibGdx project with Box2d dependency.


texts: Line rect intersection - lines behave like rays

texts:
Why is this? I have a simple ship that is a 14x14 rectangle, and a contour map. I want to be able to determine when the ship hits the ground. Here's a link to the JSFiddle.

Here's what happens now: the crosshairs indicate where the ship "exploded". The red lines indicate the ground line that was last processed. It seems that the ship explodes when it hits the ray that the line is part of.

Here's the code...

function collision() {
  for(var i = 1; i < map.length; i++) {
    var res;
    var start = new VectorPoint((i - 1) * 20, map[i-1]);
    var end = new VectorPoint(i * 20, map[i]);
    c.strokeStyle = "#ff0000";
    c.beginPath();
    c.moveTo(start.x, start.y);
    c.lineTo(end.x, end.y);
    c.stroke();
    c.strokeStyle = "#00ff00";
    var d = VectorFunctions.sub(end, start);
    var len = VectorFunctions.len(d);
    d = VectorFunctions.norm(d);
    res = rectLineCollision(start, d);
    if(res != null && res > 0 && res < len) {
      var insec = VectorFunctions.add(start, VectorFunctions.mul(d, res));
      c.beginPath();
      c.moveTo(insec.x - 10, insec.y);
      c.lineTo(insec.x + 10, insec.y);
      c.moveTo(insec.x, insec.y - 10);
      c.lineTo(insec.x, insec.y + 10);
      c.stroke();
      console.log("Res: " + res + ", len: " + len);
      break;
    }
  }
  return res != null;
}

function rectLineCollision(start, d) {
    var largestMin = -Number.MAX_VALUE;
    var smallestMax = Number.MAX_VALUE;
    for(var i = 0; i < 2; i++) {
      var n = VectorFunctions.sub(shipCopy.body[i], shipCopy.body[i + 1]);
      n = VectorFunctions.norm(n);
      // the shipCopy.body is just an array of points
      var sub1 = VectorFunctions.sub(shipCopy.body[i], start);
      var sub2 = VectorFunctions.sub(shipCopy.body[i+1], start);
      var e0 = VectorFunctions.dot(n, sub1);
      var e1 = VectorFunctions.dot(n, sub2);
      var f = VectorFunctions.dot(n, d);
      if(Math.abs(f) > EPSILON) {
        var t0 = e0 / f;
        var t1 = e1 / f;
        if(t0 > t1) {
          var swap = t0;
          t0 = t1;
          t1 = swap;
        }
        largestMin = Math.max(largestMin, t0);
        smallestMax = Math.min(smallestMax, t1);
        if(largestMin > smallestMax) {
          return null;
        }
        if(smallestMax < 0) {
          return null;
        }
      }
      else if(e0 * e1 > 0) {
        return null;
      }
   }
   return largestMin > 0 ? largestMin : smallestMax;
}


texts: When set Visual Studio as external editor tool, Unity will freeze (macbook version)

texts:
So I want to link visual studio and Unity, but if I set vs as the external editor tool and open a script, after I open a script for around 1 minute, Unity will freeze and I can't do anything but quit the application.
Also, if I set vs as external editor tool and double click on a script, visual studio won't automatically open the script, and I need to manually navigate to the script in vs to open up the script.
Can someone help me solve this problem?


texts: Calculate the near clip plane distance in meters from a certain object - Unity

texts: How do you convert the near clip plane and far clip planes to position units, to be able to find out its  distance to a game object?


texts: In Ren'py, can I make a text tag that opens a displayable?

texts:
I'm developing a visual novel in Ren'py that would benefit from an interactive glossary. Ideally, I'd like words in the text box that are included in the glossary to be highlighted, and if the user clicks on one, the glossary would open at the corresponding entry.
I see that a URL text tag is available, so I'm wondering if it would be possible to do something similar to HTML, where an <a> tag can call a Javascript function rather than an actual URL.
Failing that, I know it is possible to make custom tags, but I have not been able to find a way to use these to create an action rather than a new style.
Any advice would be most appreciated, even if it's just to say impossible, so that I can let it go and consider other options.


texts: Can an unmodifiable 3D map be one large model or many small models?

texts:
Unmodifiable meaning that any ingame actions have no result on the terrain.
Like in Source games.

Question: Should I export one large model of the map, or should I split it into smaller chunks? If so, how?


texts: My colliders keep going through one another?

texts:
So, I have some platform with colliders and a character with a collider (everything in 2D). The problem is, while there is some noticeable effects (a certain push back) when the colliders collide, they actually intersect each other and can go through each other.. How can I actually put a collider that doesn't let anything pass, it just stands there like a brick wall against anything?

By the way, any enlightenment on the inner workings of the colliders behavior will be appreciative as I cannot understand how this could even happen.

Demonstration video

Demonstration video 2

Bellow I have the images showing the inspector of both the character and platforms/wall respectively.

]4

Also: I'm moving the character using transform.position += Vector3.right * speed * Time.deltaTime;


texts: Farseer for platformer - (Almost) constant velocity

texts:
I am building the prototype for a platformer and would like to use farseer physics engine. I got the feedback that it might not be a good idea to use physics engine, but I would like to have elements like bumpers and so on.

At the moment I am looking for a good way for moving right and left (jumping is very easy). The goal is to get an almost constant velocity, so I was playing around with hight gravity and high linear damping and it is working fine, but also affects gravity. Is there a way to get a linear damping on the x-axis only or do I just have to increase gravity (which sounds a little bit strange to me).


texts: Questions about "stateless, layered multi-threaded rendering"

texts:
I have read this blog:
https://blog.molecular-matters.com/2014/12/16/stateless-layered-multi-threaded-rendering-part-3-api-design-details/
Where does a setup like this bind textures/buffers and does state(shaders, blend, rasterizer) switching?
Wouldn't that mean that is anything but stateless when i submit a command only for drawing? Drawing Command would expect correct state, wouldn't it?


texts: Handling Back Button in Android without implementing InputProcessor

texts:
Please advice/clarifyon below issue in libgdx while handling back button in Screens.

I have already gone through these 2 threads,

https://stackoverflow.com/questions/7223723/in-libgdx-how-do-i-get-input-from-the-back-button

Is there a way to capture back button twice in same activity libgdx game

As per suggestion in above two threads, I have done something like this in 2 Screen of my Game,

public class MainMenuScreen implements Screen{
    //omitted unnecessary code
    @Override
    public void render(float delta) {
    if (Gdx.input.justTouched()) {
        game.setScreen(game.STS);   //Setting 2nd Screen
    } else if (Gdx.input.isKeyPressed(Keys.BACK)) {
        System.out.println("mms back");
        //if(Gdx.input.isKeyJustPressed(Keys.BACK))
        Gdx.app.exit();            // Exiting
    }
}

public class StageScreen implements Screen{
    //omitted unnecessary code
    @Override
    public void render(float delta) {
        if (Gdx.input.isKeyPressed(Keys.BACK)) {
        System.out.println("backed to mms in android");
        //if(Gdx.input.isKeyJustPressed(Keys.BACK))
        game.setScreen(game.MMS);  //going back to Main screen
    }
}

Above code works fine, when I press BACK in Stage Screen to call Main Screen, it exits the app immediately, without stopping in my Main screen, which is as per my expectations because I am using Gdx.input.isKeyPressed(Keys.BACK) instead of Gdx.input.isKeyJustPressed(Keys.BACK).

But my problem is, when I use Gdx.input.isKeyJustPressed(Keys.BACK) method in my Screens, it does not (return true) catch BACK key.

I have already set Gdx.input.setCatchBackKey(true) for my Game.

Any idea, why does isKeyJustPressed not responds while isKeyPressed does?

Thanks in Advance.


texts: Is it more efficient to use an A* algorithm or a line system drawn in pathfinding in C#?

texts:
I was recently introduced to the A* algorithm when I asked a friend about making AI/NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A* algorithm sounds very appealing to me.

However, as I went through the Half-Life 2: Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using: a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. :(

Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy.

I'm building the game in C# (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding?


texts: How can I change displayed information as a physical control knob is slid along a track

texts:
I'm making an installation for exhibition or demonstration purpose.

I want to have a physical handle the viewer can slide along a track. As they do so, the information displayed on the screen should change, to correspond to the segment of the track the handle is currently within. Something like what's shown in this YouTube video:

https://www.youtube.com/watch?v=DOElf77g5yI&feature=youtu.be

How can I achieve this?


texts: Can I swap out Farseer physics fixtures at runtime?

texts:
I am working on a 2D side-scroller using Farseer Physics Engine v3.3.1.

In order to create a realistic physical skeleton for the player, I am using a method similar to the one explained here (See "Texture to polygon" section).

Below is my code for creating the player body:

uint[] data = new uint[Source.Width * Source.Height];

mTexture.GetData(0, Source, data, 0, Source.Width * Source.Height);

Vertices textureVertices = PolygonTools.CreatePolygon(data, Source.Width, false);

Vector2 centroid = -textureVertices.GetCentroid();
textureVertices.Translate(ref centroid);

mPhysicalDrawOrigin = -centroid;

textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 2.5f);

List<Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);

Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * Scale;
foreach (Vertices vertices in list)
{
    vertices.Scale(ref vertScale);
}

mBody = BodyFactory.CreateCompoundPolygon(mWorld, list, 1f, BodyType.Dynamic);

The player's sprite is animated, though, so the problem arises when switching states - I.e. the player is crouching or jumping. The physical body created above only reflects one state (currently standing).

Is there a way I could somehow create a body for each sprite and swap them out later?

UPDATE:

As suggested by @Nick Wiggill, I am creating one physical body per player state (I.e. walking, standing, jumping, etc) when the player is loaded, and saving them within my class. All the bodies have .Enabled = false; initially, and are only enabled when the player is in the state that corresponds to that physical body. The Bodies and their corresponding states are stored in parallel lists.

Currently, my class has a function SetState which takes care of changing the physical body when the state is changed:

new protected void SetState(object nState)
{
    //If mBody == null, the player is being loaded for the first time
    if (mBody == null)
    {
        mBody = mBodies[mStates.IndexOf(nState)];
        mBody.Enabled = true;
    }
    else
    {
        //Get the body for the given state
        Body nBody = mBodies[mStates.IndexOf(nState)];
        //Disable the current body
        mBody.Enabled = false;
        //Copy the current body's attributes to the new one
        nBody.Position = mBody.Position;
        nBody.LinearVelocity = mBody.LinearVelocity;
        nBody.AngularVelocity = mBody.AngularVelocity;
        //Set the current body to the new body
        mBody = nBody;
        //Enable the new body
        nBody.Enabled = true;
    }
}

Currently, when the game loads, a NullReferenceException is thrown when calling World.Step:
    mWorld.Step(Math.Min((float)nGameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));

In the above function, mBody is just a variable I have to keep track of the current active body. I'm not modifying the body in any other way outside of the above function, and none of the m* variables are referenced or saved anywhere outside of my class. Perhaps I am swapping the bodies incorrectly?

UPDATE:
Created a new question with the newer, slightly more specific issue:
IndexOutOfRangeException on World.Step after enabling/disabling a Farseer physics body?


texts:
I have duplicated the blend tree from the ThirdPersonCharacter (Ethan) which comes with the Standard Assets package.

In the duplicate I went into the blend tree and swapped out the walk animation "HumanoidWalk" with my own animation named "walk", but now I get a weird transition from the animation "walk" to "HumanoidRun".

Both animations, my walk animation and the original "HumanoidWalk" are root animated and look similar they have around 1.5 velocity both and same frame length.

Animation Settings:

I created the animation in blender, you will see in my video below that the animation itself runs smooth and as it should, but the transition to HumanoidRun is very weird for unknown reasons. I am using a custom metarig armature which comes with the blender add-on "rigify", I deleted some bones on the finger, but the avatar has a check and is ok (no warnings either).

Rig Settings

Player settings

I basically "copied" all the components from Ethan (ThirdPersonController) and only changed the Animator Controller and the Capsule Collider settings to match the model.

I made some short videos where you clearly see the problem, it happens if the parameter Forward is at about 0.6 - 0.8.

https://youtu.be/Q-T7FplDxLE

https://youtu.be/nrJNeo1ltsg NOTE: First I am demonstrating how it looks with the normal animations, then I add my own.

What am I doing wrong?

More Infos:

I just baked the walk animation in blender and exported it to unity again, but this made no difference.

I tried to export it from blender as FBX, it made no difference. However, I noticed that the import is happening much faster and applying in unity importer is very fast now.


texts: Could someone explain why my world reconstructed from depth position is incorrect?

texts:
I am attempting to reconstruct the world position in the fragment shader from a depth texture. I pass in the 8 frustum points in world space and interpolate them across fragments and then interpolate from near to far by the depth:

highp float depth = (2.0 * CameraPlanes.x) / (CameraPlanes.y + CameraPlanes.x - texture( depthTexture, textureCoord ).x * (CameraPlanes.y - CameraPlanes.x));

// Reconstruct the world position from the linear depth
highp vec3 world = mix( nearWorldPos, farWorldPos, depth );

CameraPlanes.x is the near plane CameraPlanes.y is the far.

Assuming that my frustum positions are correct, and my depth looks correct, why is my world position wrong?

(My depth texture is of format GL_DEPTH_COMPONENT32F if that matters)

Thanks! :D

Update:

Screenshot of world position http://imgur.com/sSlHd

So you can see it looks nearly correct. However as the camera moves, the colours (positions) change, which they shouldnt.

I can get this to work, if I do the following:

Write this into the depth attachment in the previous pass:

gl_FragDepth = gl_FragCoord.z / gl_FragCoord.w / CameraPlanes.y;

and then read the depth texture like so:

depth = texture( depthTexture, textureCoord ).x

However this will kill the hardware z buffer optimizations.


texts: How can i do a "Crouch" with only a Character Controller with no rigidbody?

texts:
I was following Bracky's fps tutorial but he didn't add crouching as an option. I took a stab at it but came up empty handed. Here is my script for player movement.
public class PlayerMovment : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;

public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;

Vector3 velocity;
bool isGrounded;

// Update is called once per frame
void Update()
{
    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if(isGrounded && velocity.y < 0)
    {
        velocity.y = -2f;
    }

    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x + transform.forward * z;

    controller.Move(move * speed * Time.deltaTime);

    if(Input.GetButtonDown("Jump") && isGrounded)
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }

    velocity.y += gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);
}

And also have a separate script for mouselook, here that is aswell.
public class Mouselook : MonoBehaviour
{
public float mouseSensitivity = 100f;

public Transform playerBody;

float xRotation = 0f;

// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update()
{
    float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);

    transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    playerBody.Rotate(Vector3.up * mouseX);
}

}
How would I go about adding one without adding a rigidbody or changing my script fully to follow other tutorials? Thank you!


texts: What's the better approach, running multiple server-builds on one instance or running one server-build and managing matches in different rooms?

texts:
We are building a racing multiplayer game using Mirror and Unity and we've been able to successfully run the authoritative server on AWS-Gamelift and Playfab so far.
Both providers are with the flexibility of running multiple server-builds and mapping with different ports.
So I think running multiple server-build for different matches on one instance is a bit expensive in terms of server usage as compared to running one server and managing multiple matches in different rooms.
But overall it seems to be a safer option to go with since build crash and similar issues will only happen on one match and other matches (servers) will be running fine on the same machine and also it's a bit easier to handle and scale.
What's your opinion on this?
It might be useful if you share any blog or resource to look at for scaling and managing servers on gamelift/playfab.
thanks!


texts: Apple iOS review and interpreted code download/execution

texts:
I'm looking for some information regarding two specifics rules of the App Store Review guidelines. More specifically rules 2.7 and 2.8 :

2.7
Apps that download code in any way or form will be rejected
2.8
Apps that install or launch other executable code will be rejected

I intend to make a multiplayer mobile game that I could update remotely. So I used a framework that allows me to use a script language (namely Lua) on the top of my engine to code game logic. My intention was to have the client submitted and validated by Apple, and then have it download the latest version of the game data (imagine a zip file with assets and Lua scripts). However this seems to be forbidden by Apple.
I do know that some rather famous game do it anyway (downloading JSON/Lua/JS files) to update their games, but I would like some clarifications.
My questions are the following :

Has anyone here made such a system on iOS ? If yes how did you deal with Apple ? Did you ask them about it ? Did you do it silently, hoping they don't notice ?

Has anyone ever been rejected because of that ? What did they say ? What was the incriminated download ?

Has anyone more information about those guidelines ? Where do they draw the line ? I suspect JSON/XML to be allowed, but it's unclear...

I imagine they could make some concession for big companies. If it's the case and you had them agree on something with you, how did you manage to do it ? Who did you contact ?

Broadly, any information regarding this would be welcome :

How did you / would tackle that issue ?
Are you aware of similar limitations for other platforms ?
Do you know a workaround for this situation ?


texts: Common pattern to scale "real units" to pixels?

texts:
This is a follow-up question to this other one.

I would like to know if there is a common/typical/best pattern to scale my representation of the world (currently 160Kmx160Km) to fit it to the drawing area (currently 800x600 pixels).

I can think of at least four different approaches:

Naïve one (the way I did it so far). I implemented a global function sc(vector) that will simply return a scaled down copy of the vector passed in. This of course works, but obliges me to write code like:

drawCircle(sc(radius), sc(position))

Wrapping functions. I could define several functions, each of them wrapping the original middleware one. For example I could define myDrawCircle that would first scale the arguments that need scaling, and then call drawCircle with the latter. This would make my code perhaps more readable and easier to maintain, but I should write a lot of wrapping functions, which sound silly.

Function decorator. I could simply decorate the existing middleware functions, providing automatic scaling for all the parameters that are an instantiation of the class Vector3D, but the problem is that those functions also work with the same parameters being list or Vector2D too, and the decorator would have no way to know which lists need to be scaled (the radius for example) and which not (the RGB values).

Surface initialisation. When defining the surface I am going to draw on, I could define the scaling factor (so that I would then use metres and not pixels as parameters). This would work transparently for me and would be my solution of choice, but of course it should be implemented in the middleware, so it's not an real option.

...anyhow: since this is a very common problem, I wonder if there is an established pattern that elegantly solves this problem that I failed to find.

PS: For this project I am using python (with pygame), but - although a python/pygame-specific answer is very appreciated, I'm more interested in the general/high-level description of the pattern rather than its concrete implementation.

Thank you in advance for your time and expertise.


texts:
I've been following the Rastertek tutorial on deferred shading (http://www.rastertek.com/dx11tut50.html). I have implemented it in my own architectural way but have ended up with the same issue as the tutorial; if you get the source and take a look, it appears to be working fine - but if you move the camera around you can see that only the front 2 faces are being rendered, and its like as if the cube is only being rendered to some kind of invisible pane - viewing from behind it is completely invisible.
In my image you can see that the model is being completely cut off. Is my 2D render texture possibly floating out in that space?

To provide the amount of code I have would be very dodgy. If you can help me out conceptually or take a look at the downloadable source code I would very much appreciate it.

Please see my attached image.

This image is from about 45 degrees to the side - it appears to be getting cut off along the red lines I've drawn (ignore the missing topside - thats just the light only going down the z plane):


texts: Multiple updates for Unity animation per one method call

texts:
I'm trying to do some simulation where I move objects procedurally in a loop within one method call. So instead of using Update(), method I do for example:

void Simulate(float deltaTime)
{
   // real logic look a lot different, this is just an example
   for(int i = 0; i < 1000; ++i)
   {
      transform.position += direction * speed * deltaTime;
   }
   .....
}

The reason I'm doing this is because I want consistent 'framerate' by passing that deltaTime parameter; Which is for example 0.01f;
And each step of that loop I'm taking snapshots on multiple cameras with calling Render() method on them before taking a picture. The movement works fine and I see it on snapshots, but some objects has an animation which should also be updated procedurally.

I've tried to do

animator.speed = 0;

and then in the same loop, to test it

for (int i = 1; i < 1000; ++i)
{
   ...
   animator.Play("WalkFWD", 0, i/1000f); //for example
}

But animation does not change over that loop. It only works with that Play method when I either make this Simulation() method a coroutine and pass one frame (yield return null), or if I use in Update().
So, my question: is it possible to procedurally update/redraw animation after normalized time of that animation is set. (without waiting for another frame)


texts: Does Macbook Air 2012 (Intel HD4000) support GLSL 1.3+?

texts: I'm using SDL2 and GLEW on OSX Mountain Lion (2012 Macbook Air) to create an OpenGL context. Querying for the GLSL version, it reports GLSL version 1.2. I'm curious if this is a limitation of the HD4000 driver, the Macbook Air/OSX, or perhaps a limitation of SDL/GLEW?


texts: Character movement relative to cursor position

texts:
I want my top-down shooter character to move towards the mouse when pressing the up arrow and strafe relative at right angles to it when pressing the left and right arrow keys.

I can't figure out how to do this.

Here is my code (The character is character_mc):

import flash.events.MouseEvent;
//Event Listners
stage.addChild(crosshair_mc);
crosshair_mc.mouseEnabled = false;
crosshair_mc.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor);

function fl_CustomMouseCursor(event:Event)
{
    crosshair_mc.x = stage.mouseX;
    crosshair_mc.y = stage.mouseY;
}
Mouse.hide();

stage.addEventListener(MouseEvent.MOUSE_MOVE,facecursor);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_KeyboardDownHandler);
//Functions
function facecursor(event):void
{
    character_mc.rotation = (180 * Math.atan2(mouseY - character_mc.y,mouseX - character_mc.x))/Math.PI + 90;

}

function fl_KeyboardDownHandler(event:KeyboardEvent):void
{
    trace("Key Code Pressed: " + event.keyCode);
    if (event.keyCode == 38)
    {
        character_mc.y = character_mc.y - 5;
    }
    if (event.keyCode == 40)
    {
        character_mc.y = character_mc.y + 5;
    }
        if (event.keyCode == 39)
    {
        character_mc.x = character_mc.x + 5;
    }
        if (event.keyCode == 37)
    {
        character_mc.x = character_mc.x - 5;
    }

}

I'm new to actionscript, so example code would be helpful.


texts: Removing inline declarations makes code work. Why?

texts:
This does not work:

camera = new OrthographicCamera(100, 100 * (Gdx.graphics.getHeight() /Gdx.graphics.getWidth()));

This does:

float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();

camera = new OrthographicCamera(100, 100 * (h/w));

I do not get the difference. One displays fine on my screen, the other remains black.

Why is this? Is there any syntactical reason why this does not work, or is it a bug?


texts: State Changes in a Component Based Architecture

texts:
I'm currently working on a game and using the naive component based architecture thingie (Entities are a bag of components, entity.Update() calls Update on each updateable component),
while the addition of new features is really simple, it makes a few things really difficult: a) multithreading / currency b) networking c) unit testing.

Multithreading / Concurrency is difficult because I basically have to
do poor mans concurrency  (running the entity updates in separate
threads while locking only stuff that crashes (like lists) and
ignoring the staleness of read state (some states are already
updated, others aren't))
Networking: There are no explicit state changes that I could
efficiently push over the net.
Unit testing: All updates may or may not conflict, so automated
testing is at least awkward.

I was thinking about these issues a bit and would like your input on these changes / idea:

Switch from the naive cba to a cba with sub systems that work on
lists of components
Make all state changes explicit
Combine 1 and 2 :p

Example world update:

statePostProcessing.Wait() // ensure that post processing has finished
Apply(postProcessedState)

state = new StateBag()

Concurrently(
 () => LifeCycleSubSystem.Update(state), // populates the state bag
 () => MovementSubSystem.Update(state), // populates the state bag
  ....
})

statePostProcessing = Future(() => PostProcess(state))
statePostProcessing.Start()
// Tick is finished, the post processing happens in the background

So basically the changes are (consistently) based on the data for the last tick; the post processing can a) generate network packages and b) fix conflicts / remove useless changes (example: entity has been destroyed -> ignore movement etc.).

EDIT: To clarify the granularity of the state changes:
If I save these post processed state bags and apply them to an empty world, I see exactly what has happened in the game these state bags originated from -> "Free" replay capability.

EDIT2: I guess I should have used the term Event instead of State Change and point out that I kind of want to use the Event Sourcing pattern


texts: Gaps appearing between Sprites when scaling the stage

texts:
  I'm learning to use createjs using this game level to-be as a sandbox: http://www.mboyeman.com/dashingdog/
  The level is composed of a single background image and 64X64pixel Sprites all coming from the same Spritesheet.
  Sprites were placed edge to edge, but spaces still appear between them when the page loads and the stage's scaleX and scaleY are set to .2 using a tween. I thought all elements of the stage should scale evenly with it, since they are its children, so am a bit lost.
         Any tips on how I can to make the whole page scale uniformly during a tween :?


texts: MonoGame: prevent command prompt in windows?

texts: Is there a way to prevent the command prompt from opening in windows when launching the game (via double clicking)?


texts: What considerations should I be aware of when placing an Unreal project under source control?

texts: I want to give it a try to creating a git repository from my UE4 project and uploading it to Github.com but I wonder what special considerations should I have to avoid posting sensitive information like my developer key/certificate, or avoid adding large binaries files, or temporary/intermediate files.


texts:
Looking at example code for mesh deformation in unity

https://answers.unity.com/questions/746673/sine-wave-mesh-deform-with-different-directions.html

And i see theyve used

 public Transform Target1;
 public Transform Target2;

 void CalculateWaves ()
 {
     waves[0].Direction = Target1.position - transform.position;
     waves[1].Direction = Target2.position - transform.position;

And i dont understand the difference between Target1.position and transform.position without any reference to an instance.

Arent they the same thing. And how does transform.position function without a reference.


texts: Selecting the closest point in perspective view mode

texts:
I'm trying to improve my algorithm for selecting points in perspective view mode (OpenGL/Qt/C++). The current implementation works as follows.

The user clicks on a certain (x,y) position (in Window space)
Traversing the pipeline from Window space back to World space (that is, Window → NDC → Clip → Eye → World), this defines a point a on the near clipping plane and a point b on the far clipping plane
The distances from the line between a and b and the vertices (available in World space) are determined (see e.g. this article on Wikipedia)
The point with the minimum distance to the line is selected

Now, this works fine when using orthogonal view mode. However, when visualizing something in perspective view mode, there are some cases where the result might be a bit off.

As example, let's consider the wireframe of a cube. In the illustration below, the point (x,y) is the point where all white lines meet. These lines are orthogonal to the line from a to b which is not visible in this orientation — the second illustration shows a rotated view.

The point that eventually gets selected is highlighted in green. However, as the blue point seems to be closer to (x,y) in perspective mode, the user probably expects this point to get selected instead. Somehow the computed distances have to be scaled in order to take this effect into account. How is this usually done?


texts: Changing color for each element in linerenderer not working

texts:
I want to change color for each line (element) just like in color switch. But my code is not working. What I wanted is that the right line should turn blue then the down line should turn color red. What is wrong with my code?

void Start()
{
    lineGeneratorPrefab = new GameObject();
    DrawLine();
}

private void DrawLine()
{
    GameObject myLine = new GameObject();
    myLine.transform.position = start;
    myLine.AddComponent<LineRenderer>();
    LineRenderer lr = myLine.GetComponent<LineRenderer>();

    lr.positionCount = 4;

    lr.SetPosition(0, new Vector3(-2, 0, 0));
    lr.SetPosition(1, new Vector3(2, 0, 0));
    lr.SetPosition(2, new Vector3(2, -2, 0));
    lr.SetPosition(3, new Vector3(-2, -2, 0));
    lr.materials[2].color = Color.blue;
    lr.materials[3].color = Color.red;
}


texts: How can I open the map in Skyrim using Papyrus or SKSE?

texts:
While making a mod for Skyrim, I'd like to allow a player to chose a location to teleport to.

Essentially, I'll be:

enabling Fast Travel if disabled
changing fast travel speed so that the travel happens near instantly in game time
opening the map to allow player to select destination
resetting fast travel speed, disabling fast travel if appropriate

It's the third dot point I need help with. I can work out the others with Papyrus script, but is there a way to open the Map using Papyrus or SKSE?


texts:
I'm looking for a very simple way to put up 2 teams out of unspecified amount of players. So its not actually a standard matchmaking since it only creates one match out of the whole pool of queued players.
I do have pretty much only single variable and it is the ELO score for each player, which means it's the only available option to base calculations on.

What I thought of is just simply go through every possible combination of a players(4 in each team) and the lowest difference between the average ELO of teams is the final rosters that get created. But it would be the most unoptimized way to do that.

So I decided to ask a question in here, maybe you can help me with that in some way.


texts:
In my code, I wanted to use the spritecollides method but I got the following error message:

Traceback (most recent call last):
File "/Users/lanik2009/Documents/pygame testing.py", line 76, in <module>
hits = pygame.sprite.spritecollide(player, obstacles, False)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pygame/sprite.py", line 1645, in spritecollide default_sprite_collide_func = sprite.rect.colliderect
AttributeError: 'pygame.Rect' object has no attribute 'rect'

My code:
import pygame

pygame.init()

white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)

w = 500
h = 500

x = 15
y = 480

vel = 5
screen = pygame.display.set_mode((500, 500))

square = pygame.image.load(r'/Users/lanik2009/Downloads/square.PNG')
square = pygame.transform.scale(square, (46, 40))
triangle = pygame.image.load(r'/Users/lanik2009/Downloads/triangle.PNG')
triangle = pygame.transform.scale(triangle, (46, 40))

squareSprite = pygame.sprite.Sprite()
squareSprite.image = square
squareSprite.rect = square.get_rect()

triangleSprite = pygame.sprite.Sprite()
triangleSprite.image = triangle
triangleSprite.rect = triangle.get_rect()

def drawer():
    screen.fill(black)
    screen.blit(triangle, (100, 460))
    screen.blit(square, (300, 460))

jump = False

obstacles = pygame.sprite.Group()

obstacles.add(squareSprite)
obstacles.add(triangleSprite)

running = True

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        x -= vel

    if keys[pygame.K_RIGHT]:
        x += vel

    if jump == False:
        y = 480

    if keys[pygame.K_UP]:
        y -= 40
        jump = False

    if event.type == pygame.KEYUP:
        jump = False

    drawer()

    player = pygame.draw.circle(screen, white, (x, y), 10, 500)
    pygame.display.update()

    hits = pygame.sprite.spritecollide(player, obstacles, False)
    if hits:
        running = False

pygame.quit()


texts: Why is this Mono Behavior in the animator?

texts:
I'm looking through the 3D Game Kit from the asset store to accustom myself with the animator, and I'm just wondering what this is referring to.
I was looking into controlling MonoBehaviors through the animation controller the other day and thought I had come to the conclusion that it couldn't be done directly, so what's this?


texts:
I have two canvases. One with a background image and one with all overlaying elements like texts and such.

The background canvas has an order of 0, the overlay canvas of 1.

Now, I'd like to create an animating sprite on top of those canvases but I can't for the life of me get the sprite on top of the other images.

I can see the sprite being on top on the stage, but when I switch to gameview, it's gone! There are no scripts attached to the sprite. Only an animator(Which works fine when I play it).

Note:

My canvases have a render mode of
Screen space - Overlay.
I've set the spriterenderer on
Sorting Layer 9, order 300. Although
it's  the only sprite out there.
layer 1 or order 1 didn't do anything
different, though.
The other elements in the canvases are either UI texts or Images
All the elements in the canvases are on either BackgroundLayer or OverlayLayer
The canvases themselves are on the UI layer


texts:
Using libGDX, sprites or simply texture regions must be inserted into the batch for drawing:

void render()
{
    batch.begin();

    batch.draw(...);

    batch.end();
}

Is the VBO being uploaded to the GPU in every frame?
Is there a way to reuse the batch once any of the data changed?


texts:
I have a player rotating by the mouse and want the bullets line up with the player's gun. Right now they simply come from the point of the player and shoot in the direction of mouse. I just need the bullets to line up with the player's gun as he rotates, rather than at a fixed position. Sorry my math is a little rusty and not sure how to achieve this. I've marked the two spots where I know I need to change.

  var player = {
  x: (canvas.width/2),
  y: (canvas.height-60),
  vx: 0,
  vy: 0,
  Bullets: [],
  draw: function() {
    ctx.save();
    ctx.translate(canvas.width/2, canvas.height-60);
    ctx.rotate(Math.atan2(mousePos.x-this.x, this.y-mousePos.y));
    ctx.drawImage(img, 0, 702, 42, 64, -21, -33, 42, 64);
    ctx.restore();
  },
  shoot: function() {
        var angle = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
        this.Bullets.push(Bullet({
        radian: angle,
        speed: 6,
        x: player.x, //<-- Here
        y: player.y, //<-- And Here
      }));
    }
};

function Bullet(I) {
  I.active = true;
  I.radian = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
  I.xVelocity = -I.speed * Math.sin(I.radian);
  I.yVelocity = -I.speed * Math.cos(I.radian);
  I.width = 3;
  I.height = 3;
  I.color = "#000";

  I.inBounds = function() {
    return I.x >= 0 && I.x <= canvas.width &&
      I.y >= 0 && I.y <= canvas.height;
  };

  I.draw = function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  };

  I.update = function() {
    I.x += I.xVelocity;
    I.y += I.yVelocity;

    I.active = I.active && I.inBounds();
  };
  return I;
}

I have tried using the following,

x: Math.cos(mousePos.x- player.x),
y: Math.sin(player.y - mousePos.y),

But the bullets only comes from the top left screen (with the mouse click on the bottom right). Would it have to do with the translate that I doing on the player?


texts: Negative timeout value in Variable Timestep loop

texts:
I was working on my game loop and I came across an odd problem. The loop was working fine, my states could render, received updates, etc. I then proceeded to create my Input system, which, also works. However, after implementing that I continually & randomly receive a Exception in my thread stating:
Exception in thread "Thread-3" java.lang.IllegalArgumentException: timeout value is negative

I first tried to debug this. The problem is there is 0 consistency with the exception occurring. KeyEvents seem to have no affect, due to the fact I can use the poll system & not generate an exception. That & sometimes upon running it automatically throws an exception. I've re-looked through the code and I'm not quite sure what is causing this.

For convenience I'll just leave the relevant code.

public class Game implements Runnable {

public int FPS = 0;

private Double delta;
private long lastFps = 0;

private final int TARGET = 60;
private final long OPTIMAL_TIME = 1000000000 / TARGET;
private boolean gameRunning = false;

@Override
public void run() {

    long lastLoop = System.nanoTime();

    while (gameRunning){

        //Figure out how long its been since last update - used for entity calculation
        long current = System.nanoTime();
        long updateTime = current - lastLoop;
        lastLoop = current;

        delta = updateTime / ((double)OPTIMAL_TIME);

        lastFps += updateTime;
        FPS++;

        if(lastFps >= 1000000000){
            System.out.println("(FPS: "+ FPS +")");
            lastFps = 0;
            FPS = 0;
        }

        //Updates state + calls render
        updateState();

        /*
         * We need each frame to take 10mill-sec
         * Take recorded time + 10 milli
         * then factor current time
         * this ^ is final value to wait
         */
        try{
            Thread.sleep( (lastLoop - System.nanoTime() + OPTIMAL_TIME) /1000000 );
        }
        catch(InterruptedException exception){
            exception.printStackTrace();
        }

    }

}

Unless the KeyEvent's could possibly have relation to the problem or my input polling (Which doesn't manage time or anything affecting the thread) I'm not sure if it's needed to post any relevant code from that class. (If you think I need to you're welcome to ask but it's just boolean arrays + a string cache).

The question: Why is the thread encountering a negative timeout value?


texts: How do I make camera follow the player within some bounds?

texts:
I am creating a simple ambient/explorer platformer. Because I want the player to only be able to see a new area once they have reached it, I decided to split up the world in rooms.

To not make things like pushing boxes from room to room overly complicated, this camera behavior is implemented by simply adding or subtracting the screen width/height to/from the camera when the player is out of the screen bounds.

Or, in pseudocode:

if(player.x < camera.x)
    camera.x -= screen.width;
if(player.x > camera.y + screen.width)
    camera.x += screen.width;
if(player.y < camera.y)
    camera.y -= screen.height;
if(player.y > camera.y + screen.height)
    camera.y += screen.height;

However, I also want to implement a slight parallax effect. For this I obviously need to move the camera around a little. So I need rooms that are slightly bigger than the screen size, and to make the camera follow the player until the player is at one of the sides of the room.

How do I create a smooth camera movement for this?