texts: How would I load a new scene when a score that is stored in a string is reached?

texts:
This is a code that I am working on for a space shooter. Part of it works and my score does increase by 7 every second while being loaded into a GUI box, but my script does not load my scene when the number reaches 1000. I have made sure that my scene is a part of my build settings and I have tried some fixes but it doesn't load even though I don't get any sort of error. Any Ideas?

#pragma strict
function Start(){
InvokeRepeating("EachSecond",1.0,1.0);
}

var score: int = 0;
var addscore = 7;

function EachSecond()
{
score=score+addscore;
}

function OnGUI(){
GUI.Box(Rect(1000,10,100,25), score.ToString());
}
function WinningScore()
{
     if (score >= 1000 )
     {
          Application.LoadLevel("Win");
     }
  }


texts: Visual Studio Code Unity AutoComplete still not working

texts:
I am having an issue with Visual Studio Code AutoComplete for Unity.

Some of the autocomplete is working, such as: void Start(), void Update(), but most of the rest of Unity Autocomplete is not working such as: GameObject, Rigidbody, Input.GetKey, etc..)

I know VScode and Unity are not connected like how Unity and Visual Studio are, but it seems that a lot of people make it work somehow, so I thought it is possible to make it work without much trouble.

I have the extensions needed to make it work (C#, Unity Tools, Unity Snippets Code etc...)
I have set vscode as my script editor (Unity -> Edit -> Preferences -> External Tools)
I installed  .NET Core SDK and .NET Framework 4.6 Targeting Pack
I tried uninstalling Unity and vscode but that didn't work either...

How can I solve this?


texts: Is it possible to have the main callback functions in different files with love2d?

texts: Is it possible to have love.load(), love.draw() and love.update() in different files? and if so how would I go about doing that?


texts: Canvas not filling up the whole screen in Unity 5

texts:
I am trying to make my canvas auto resize to any screen size. These are my canvas scalar settings:

UI mode: change with screen size

match height and width

reference resolution: 600x800

I looked up in various tutorials where they say to set it to "change with screen size" and "match height and width" so I did that but still it's not fitting. The weird thing is that it fits horizontally but not vertically.

screenshot: https://s15.postimg.org/ue99zehkr/Screenshot_20161207_132731.png


texts: Why is my Mesh reference being marked (Clone) after I add a new component?

texts:
I have a script that creates a quad mesh, saves the mesh as an asset, and assembles a game object based on some parameters. If I add another component to the GameObject after, the mesh is marked "(Clone)".
gif for reference. This all happens in code but results are the same when doing it manually.

-
When I drag the object to the project view to make it a prefab, the Mesh Filter loses it's Mesh reference. It's fine if I manually assign the mesh afterwards but that defeats the purpose of doing it this way.
To be clear, if I don't add this (or any) component, it works fine and can be made into a prefab without issue.


texts: Pathfinding with non-deterministic transitions between nodes

texts:
Consider a map not unlike a board game, where some of the moves are made non-deterministic. For example, moving onto certain cells will require you to roll a dice to determine where you should move next. The map, I would like to navigate agents through have similar characteristics:

Some of the map nodes have deterministic connections while others do
not (e.g. rolls a dice)
The move random events can have more than two outcomes, in fact most of them have many (e.g. move to random node in certain radius)
there are various distances (cost) between nodes

What algorithm(s) can be used to find on average the shortest path through such map for an agent? Though not required a nice bonus would be configurable risky-ness or confidence the path will 'work'.

Some time after asking I realized the is a major problem with the question - there is no path. Because agents can stray from planned path unexpectidly, rather than ordered sequence of nodes the algorithm should find goal direction/distance from every node, much like reachability/distance output from Dijkstra's algmorithm.


texts: How to achieve this additive blending effect in Unity shader?

texts:
I want to achieve something like this using blending

I thought that it might be a simple additive shader but after using Blend One One or Blendop Add I get something like this


texts:
I'm trying to implement an input listener for FNA (modern version of XNA). Since FNA does not supply any sort of way to listen to native input this has to be done through the windows API and native calls. This is how I set this up:
public KeyboardListener(GameWindow window) {
    var procedurePointer = Marshal.GetFunctionPointerForDelegate<WindowProcedure>(Procedure);
    procedure = new IntPtr(SetWindowLongPtr(window.Handle, GWL_WNDPROC, procedurePointer.ToInt64()));
    if (procedure == IntPtr.Zero)
    {
        var error = GetLastError();
        throw error switch
        {
            ERROR_INVALID_WINDOW_HANDLE => new InvalidOperationException("Invalid window handle"),
            _ => new InvalidOperationException($"Unknown error message '0x{error:X4}'")
        };
    }
}

// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlongptra#parameters
private const int GWL_WNDPROC = -4;

// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowLongPtr(IntPtr hWnd, int nIndex, long dwNewLong);

[DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetLastError();

I construct the keyboard listener during the Initialize method of Game:
class MyGame : Game {
    protected override void Initialize() {
        new KeyboardListener(Window);
    }
}

This is the method call that reports the error: SetWindowLongPtr(window.Handle, GWL_WNDPROC, procedurePointer.ToInt64()) and it throws "Invalid window handle". It's worth noting that the example code I saw converted the pointers to Int32 instead of Int64, but I am on a 64 bit machine so the pointers can not fit in 32 bits.

What I've tried & figured out so far...

Debugging tells me that both window.Handle and procedurePointer
are non-null and at least point to something.
I have tried to initialize it earlier or later, but that doesn't seem to make a
difference.
Other native methods such as SDL2.SDL.SDL_MinimizeWindow(Window.Handle) work perfectly fine and don't complain about the window handle.


texts: Get vector3 position of Cursor on a fixed 2D plane within a 3D scene

texts:
How is it possible to get a cursors X and Y Location relative to the scene planes rather than using co-ordinates based upon pixels of screen height and width?

I have the start of a very basic game, picture with a few physical aids shown below.

I want to find out how far away the cursor is on the X and Y axis from an object in the scene.
The Z axis is irrelevant due to the nature and orientation of the game, so z = 0. (Note that in Unity, the Y axis is vertical)

Basically, the distance of the cursor from the cube on the X Axis upon clicking will define the power of an action.

Because of this. I want to get the cursor X position relative to the 0 point of the scene ( or the object ), not relative to the bottom left corner of the screen.

I could then use Vector3.Magnitude() to get the distance.

How is this possible?


texts: Managing cross-platform targets/compatibility with Monogame

texts:
I recently started using Monogame for the first time because of it's cross platform compatibilities and heavily active development. The first thing I did is installing the whole framework using their provided installer, but as soon as I wanted to make my first Monogame project, I noticed the following:

Although being cross-platform, there is no real 'Monogame' library. The framework ships with multiple assemblies for several platforms, each with their own dependencies. This is reflected both in the Visual Studio project templates as well as for the nugets they provide.

Now I'm wondering: Is there a straightforward way to just develop with the Monogame framework 'itself' in the first place, and then deciding on platform etc. later by using build targets and conditional compilation? Or do I just have to reference every assembly and it will work out of the box? What's your approach when developing with Monogame for different platforms? Making a .NET project for every target platform?

Their documentation unfortunately doesn't describe the different platform assemblies. They are just there, ready to be used with the infomation that Monogame IS cross-platform compatible.


texts:
I was wondering, how would I go about creating hidden loading scenes with UDK? For example, a character walks in to an elevator, the elevator fakes movement, whilst the previous floor is destroyed and the next floor is loaded on top.

I assume it's possible with UDK, since it's supposedly rather flexible, but I've never used UDK before (I decided to ask this question first to save me learning it all, finding out it isn't possible, then giving up).

So yeah, is hiding the loading process possible? And if so, how would I go about doing it?


texts: Changing some color of a texture using C# in Unity

texts:
It's almost 2 days that I'm looking for a way to do this in Unity using C#, but still no luck.

Imagine you have a texture with different colours (this texture can be a rug), and you just want to change the colour of the parts that you click on it. e.g. I click on blue and the blue part turn into yellow. take into consideration that the parts we click on it are irregular.

The images are png, but created in Photoshop using different layers. for example, in the following texture, we have 2 colours of pink and purple. if I click on purple I want it to become yellow, and if I click on pink I want it to become green

How can I do it in Unity C#?

Thanks for all your helps.


texts:
I want to make a 3D voxel game, randomly generated planets, some with live (one minimum with life) , and they are spinning around the sun. For now I have this in OpenGL 2.1 (using fixed pipeline, glBegin / glEnd), and this planet and sun is sphere made out of triangles not blocks, and you will be able to travel to the other planets with your custom made spaceship:

And I have a couple of questions:

Is it ok to use OpenGL 2.1 or should I use OpenGL 3.3+
Do I need shaders to do something like not rendering block that are not visible
Do you have some resources for voxel games?

And finally sorry for my English.


texts:
I want to rotate a sprite so that it faces the mouse cursor/screen touch location. Currently I'm using the following method to compute the angle of rotation. The input position is the target point the sprite must face:

- (void) moveToPosition: (CGPoint)pos
{
    moveTarget = pos;
    const float targetX = (moveTarget.x - self.position.x);
    const float targetY = (moveTarget.y - self.position.y);
    const float angle   = atan2(targetX, targetY);
    targetAngle = ClampF(CC_RADIANS_TO_DEGREES(angle), -180.0f, 180.0f);
}

Then in the update method, which is called every frame, I do a linear interpolation between the target angle and the current, to ensure a smooth rotation:

- (void) update
{
    const float currentAngle = self.rotation;
    if (currentAngle != targetAngle)
    {
        const float newAngle = LerpF(currentAngle, targetAngle, [self getTurnSpeed] * Time.deltaTime);
        self.rotation = newAngle;
    }
}

This setup works OK, except when the target angle gets close to 180/-180 degrees. When it gets there the sprite just spins the whole way around in a very wacky manner. I've recorded a short video to illustrate.

Which would be the best way to handle these cases, when the angle wraps, and fix this weird spin effect caused by it?


texts: Is it legal to copy stats and abilities of characters from another game?.Please note that my game does have a similar gameplay to the game I am copying. My characters will look different of course.


texts: Creating a master server for Unity game (Unity 2017)

texts:
I have a basic FPS game made in Unity. I am using the Unity NetworkManager, NetworkManagerUI and NetworkIdentity components that came with Unity.

The game is working fine on my local network when I make one pc a client-host and other a client.
It is also working great using the 'Mulitplayer' service that is free with Unity (for up to 20 max over all games/projects etc, and is supposed to be only for testing I believe)

I'm 99% sure it is possible to run a 'server version' of my app on a pc in my home, and make this into a dedicated master server, but I cannot find much at all from Unity officially regarding this (It seems to always point me to just extending my deal with them to get more players into the server they provide, for which the costs are 1000x more than the budget I have for the game)

Before Unity were offering these pricey services, there was info such as this: https://unity3d.com/master-server

But it says that is only compatible with Unity 3.x

I've asked this question 2-3 times already on the Unity Answers site, and there are no answers at all. I've also browsed it for similar questions and all those seem to be unanswered or way out-of-date.

As I stated last time I ask this, I know thatt Rust game is made with Unity. In past, I downloaded (officially from Facepunch, the devs of Rust) the 'Rust Dedicated Server' application, which I ran on my desktop PC (with fibre network connection) and then I was hosting a server in game. The server ran smooth as silk, so for my game I dont think i would need an actual modern server machine or direct internet connection (otherwise, how did Rust manage it??)

So as I say, I have the network functionality all up-n-running. But the last piece of the puzzle is that I'm using Unity's Mulitplayer Service, and this only allows 20 max concurrent players. This isn't quite enough, as I'd like to have at least 50 if possible. Also I would end up running 10-20 of these so that there is a choice of 'rooms'. Ideally I would be able to let people download and run their own just like Rust.

Before I got to this stage, I was trying to make one user become the Client-Host, but I couldn't figure out how the other clients would be able to tell what is the IP address for the host.

Please can anybody help me, I feel like I've gotten the majority of the way there but now I can't get any further by myself.

Many thanks!


texts:
I want to use Unity on Android. How can I integrate Unity with Eclipse?

I searched this site and various forums, but found nothing useful.


texts: Implementing a wait function in a game script

texts:
I have been implementing behavior for enemies in my game and so far I have been doing it sort of like below:

public void update()
{
    if (frame > 60 && frame % 30 == 0)
    {
        shootAtPlayer();
    }
    frame++;
}

Which is meaning after frame 60 shoot the player every 30 frames. The frame-count is important as the game is fixed frame-rate and everything is relying on this at the moment. There are many small scripts for enemy behavior like above and I currently iterate through each one calling update(). I have realized it will quickly get unweildy dealing in absolute frames and I want to move towards a pattern where I can specify to do X for 60 frames then do Y e.t.c, something that is easily understandable and easy to write. I want to go for something like below:

wait(60)
while(true)
{
    shootAtPlayer();
    wait(30);
}

I was wondering if there is a design pattern that would easily support such a syntax. My initial thoughts were to create a thread for each script object and have the wait implemented similar to below:

wait(int frames)
{
    while(frames > 0)
    {
        frames--;
        suspend();
    }
}

with the method running the scripts calling resume in turn on each script. I could potentially have up to 300 scripts running at once which would mean 300 threads to handle. Am I taking the correct approach to solving this problem?

I am programming this in C# XNA.


texts: What is the best landscape and portrait resolution ratios that will fit the most of the devices out there and the black bars size will be minimum?


texts: How can I make a "random" generator that is biased by prior events?

texts:
I am looking to implement a chance based system which is biased by prior event.

Background:
Some years back, I remember an update for World of Warcraft announcing that they implemented a new chance calculator that would counteract spiky chains of events. (e.g. making critical strikes or dodging several times in a row). The idea was that in the event that you would dodge a hit, the chance that you would dodge the next hit would be diminished, but it would work both ways. Not dodging a hit would equally increase the chance of dodging the next hit. The major trick here, was that over several trials the dodge chance would still correspond to the percentage given to the player in his or hers stat-sheet.

This kind of system very much intrigued me at the time, and now I am in the situation of needing such a solution.

Here are my troubles:

I am guessing that I would be able to find online resources on implementing such a system, but I may just be lacking the relevant buzz words for finding it.
Also I need this approach to fit a system that is not binomial (i.e. two outcomes), but instead contains 4 mutually exclusive events.

My current approach is similar to that of a raffle ticket system. When an event occurs I change the weights in favor of all other events. This could work if the four event were meant to be equally likely, but in my case, on needs to be much more prevalent. But as the prevalent event happens more often, it shifts the weights of the other a lot higher than intended and I cannot seem to find the numbers for the weight shifts that are needed to keep the average ticket count around the initial values that the event were given.

A few direction pointers or a clear cut example would be much appreciated.


texts: How can I generate isometric sprites based on a 3d model?

texts:
I'm wondering about the following:

I'd like to create isometric sprites for a game that I'm currently developing.

Rather than asking an artist to draw numerous sprites (which will be quite costly), I'd prefer to purchase a 3d model, for a platform such as Blender or 3DS Max, in order to render these models at different angles in an isometric perspective.

Depending on the level of detail, for each angle (0-359 degrees), I would need a sprite. Is there a specific script or feature available in either Blender, 3DS Max or a similar tool, that would suit my purpose?

Thanks a heap!


texts:
got another question here. Its not about actually writing/reading files in XML, i already know how to-do this. But rather something that has bugged me for awhile.
Ok, so when i write out my files, they look like this:

<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
 <Asset Type="ProjectWitch.Animation">
      <Filename>C:\Users\Daniel Randell\Desktop\Project Witch\Project Witch (MAIN)\Project_Witch (MAIN)\Project_Witch (MAIN)Content\player.png</Filename>
      <CurrentFrame>0</CurrentFrame>
      <Number_Of_Frames>1</Number_Of_Frames>
      <Max_Time_Per_Frame>0</Max_Time_Per_Frame>
      <Animate_Once>0</Animate_Once>
      <Using_Image>1</Using_Image>
      <Rect>
        0    166  64   58
      </Rect>
      <Vector2>
        12   12
      </Vector2>
      <Rect>
        81   71   51   59   False
        80   71   13   43   True
        121  71   12   22   True
        130  82   7    41   True
        89   63   11   23   True
      </Rect>
 </Asset Type="ProjectWitch.Animation">

As you can see the problem, it should write out at the end:

      </Asset>
 </XnaContent>

But it's always writes out the:

 </Asset Type="ProjectWitch.Animation">

Its a bit annoying to keep having to look into the XML files and deleting this, so i'm wondering what i'm doing wrong?

Saving Code:
http://pastebin.com/yyC3q3aS

Thanks for any help :).


texts: How can I get the position of a fixture in Farseer Physics 3.5?

texts:
I created a body(rectangle). After that, I attached a circle shape to the body.

I need the position(world coodinates) of the circle shape because I want to draw a circle sprite(Texture2D) on that position.

How can I get the world coodinates of the fixture?

Body Rectangle;
Rectangle = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
Rectangle.BodyType = BodyType.Static;
Rectangle.Position = new Vector2(4.8f, 6.4f);
Rectangle.Rotation = (float)(60 * Math.PI / 180);

CircleShape = new FarseerPhysics.Collision.Shapes.CircleShape(0.5f, 1.0f);
CircleShape.Position = new Vector2(1.0f, 0.0f);
Fixture fixture = Rectangle.CreateFixture(CircleShape, 1.0f);


texts: Converting back and forth between spherical and cartesian coordinates in glsl

texts:
I have checked all the possible resources and I still don't know why my code is not working.

This code should convert uv (texture coordinates) or cartesian into spherical and back. But my code still can't convert the values back properly, even though it is the same as under that link:
http://mathworld.wolfram.com/SphericalCoordinates.html

#ifdef GL_ES
precision mediump float;
#endif

#extension GL_OES_standard_derivatives : enable

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;

const float PI = 3.14159265359;

vec2 toUV(vec3 n)
{
    vec2 uv;

    uv.x = atan(n.y, n.x);
    //uv.x = atan(n.y / n.x);   // Doesn't work either
    uv.y = acos(n.z);

    return uv;
}

// Uv range: [0, 1]
vec3 toSpherical(vec2 uv)
{
    float theta = 2.0 * PI * uv.x;
    float phi = PI * uv.y;

    vec3 n;
    n.x = cos(theta) * sin(phi);
    n.y = sin(theta) * sin(phi);
    n.z = cos(phi);

    // x, y, z range: [-1.0, 1.0]
    return n;
}

void main( void ) {
    // Range from 0 to 1
    vec2 p = gl_FragCoord.xy / resolution.xy;

    vec3 color = vec3(0.0);

    // The point of a sphere with radius 1.0
    vec3 n = toSpherical(p);

    // The cartesian coord
    vec2 uv = toUV(n);

    color = vec3(uv, 0.0);

    // uv should be p by now
    //color = vec3(p, 0.0);

    // Showing the color
    gl_FragColor = vec4( color, 1.0 );

}

To view this code, you can just paste everything into this site's editor http://www.glslsandbox.com/e

Any help would be appreciated.


texts: Are there any good books for GameMaker:Studio?

texts:
I'm just wondering if there are any good books for the GameMaker:Studio software?

I want to using it to prototype my projects and will be travelling for the next few days so I thought it might be a good time to familiarize myself with it. I see that there are a ton of tutorials online, but I won't have internet for most of my travels so I'm really looking for an offline resource, thanks.


texts:
How would one approach developing an AI for a trading card game(e.g. Magic The Gathering, YuGiOh, etc.)?

I'm not sure where to even begin. How would "Easy", "Normal", and "Hard" AI difficulties differ under the hood?


texts: MonoGame window is huge although it should be small

texts:
I'm using Monogame to create a simple game.

In my Game1 class initializer I set this:

Graphics.PreferredBackBufferWidth = 1280;
Graphics.PreferredBackBufferHeight = 1024;
Graphics.ApplyChanges();

My screen resolution is 2560x1600, so the window should be relatively small on startup. However, it's filling the entire screen and more. Why is that? I'm new to this so I have no idea what other information you might need to help me.

Thanks

EDIT: Okay, it had something to do with me messing with the Configuration Manager. There, I tried adding x64 support (no idea, if that's necessary). I'm not sure what I did there, though. I thought I deleted everything I added. However, after reverting the project to the last commit, the problem is gone. What happened there? Any ideas?


texts: Is using XNA title storage for level/config files a Bad Idea?

texts:
I've reached the point in development where my Game Engine can actually do stuff, and it's time to start thinking about how to store / load the various bits and pieces where they need to be.

I've decided to go with file storage (rather than a database), which means I'm probably going to be using .xml, .json, or .csv files. The only remaining question is how to actually store them within the game's binaries (so that any players won't be able to edit levels willy nilly).

XNA's Title Storage, being read-only, seemed as good a starting place as any, but when I loaded up the MSDN page, there's this warning on the top:

  This topic describes how to add files to title storage that the game will access through stream I/O. This is the exceptional case, and is not recommended for most XNA Game Studio games. Instead, consider using the Content Pipeline to manage your game data most efficiently.

Emphasis mine.

So is it a bad idea to use Title Storage for level/config files, or is that warning intended to stop people from using it to store things like Texture2Ds and SpriteFonts ?


texts:
This may not be the best forum for this question, but I know a lot of you have dabbled in the field of general AI for games so here it is.

I'm doing the cliche population evolution of creatures in a simulated ecosystem (with some cool irrelevant twists) where each creature is its own neural network. Specifically, I'm using the NEAT algorithm to evolve creature brains over generations.

My problem is that I can't figure out what to feed as input to the creature neural networks. I haven't found any relevant literature on it either.

The world right now is composed of prey/predator creatures and grass for the prey to eat. I want all creatures to see all three objects (prey, predators, and grass). The other important point is that the populations are not fixed. Prey can become endangered, grass can become limited, etc.

Initially I was going to have a list of all objects as relative positional vectors within a radius of a given creature as input, but variable sized inputs are basically a no go for neural networks. My second idea was just show everything in the scene (even if it may be a sensory overload), and when an object dies just replace it with a -1 hot vector. But that would just confuse the ANN.

I'm out of ideas and flailing in the water. Any thoughts are appreciated.


texts: How can I have the character come back to its full height after crouching?

texts:
I'm making a simple game and when the player crouches/slides I would want to make the character to change size. However when it changes to its smaller size it doesn't go back to its original size after you release the crouch button.
using UnityEngine;

public class advancedMovement : MonoBehaviour
{

    PlayerMovement basicMovementScript;
    public float sprint = 5f;
    public float slideSprint = 6f;
    public float deceleration = 0.5f;

    public CharacterController ccr_controller;
    public float ControllerHeight;

    // Start is called before the first frame update
    void Start()
    {
        basicMovementScript = GetComponent<PlayerMovement>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift))
            basicMovementScript.speed += sprint;
        else if (Input.GetKeyUp(KeyCode.LeftShift))
            basicMovementScript.speed -= sprint;

        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            basicMovementScript.speed += slideSprint;
            ccr_controller.height = ControllerHeight;
            ControllerHeight = 7f;
        }

        if (Input.GetKeyUp(KeyCode.LeftControl))
        {
            basicMovementScript.speed -= slideSprint;
            ccr_controller.height = ControllerHeight;
            ControllerHeight = 14f;
        }
    }
}


texts: How are the same items generated with slightly different attributes?

texts: Consider games like Destiny.  How do they generate weapons that have the same skins and names, but different attributes?  Two people can have the same weapon or armor piece, but have different attributes on these pieces based on luck or drop rate etc.  How is this accomplished programmatically?


texts: Only render/calculate the chunks in frustum!

texts:
I have a 2D world in form of a Block[][]-Array that holds all the blocks of the world. Every block has it's own Box2D Body (I want a "minecraft"-like 2D world for this project). Naturally I don't want to calculate all the box2D-bodies at the same time and I don't want to render what's not on screen neither (SpriteBatch).

So I divided my huge world into "Chunks". They are all of the same width and height. Now I'm a bit stunned though.

Each chunk starts at (0,0) which is the lower left corner of the chunk. Now in my player-class I do the following (if the player has moved)

public void calculateChunksToRender()
{
    for(int x = (int) this.getPosition().x - Chunk.chunkWidth * 2 - (Chunk.chunkWidth / 4); x >= 0 && x <= game.getMap().getWidth() - Chunk.chunkWidth && x<= (int) this.getPosition().x + Chunk.chunkWidth; x++)
    {
        if(x % Chunk.chunkWidth == 0)
        {
            Vector2 chunkPosition = new Vector2(x, 128);
            System.out.println(chunkPosition);
            chunksToRender.put(chunkPosition, game.getChunkMap().get(chunkPosition));
        }
    }

As the start point of the x-coordinate in the chunk is on the left side, I go 1 3/4 chunks to left and render it, if still visible. Why 1 3/4? Because that way when I'm 3/4 to the right I don't see the left chunk anymore, so I don't need to render it. For the right chunk I do the same, but only with Chunkwidth... I guess it's pretty self-explanatory though.

Obviously this is just the X-dimension and I'm not sure if there isn't a far better way to do this.
Why? Because, well, right now I have 3 chunks to render, but basically I have a 8-neighbourhood around the one chunk the player is currently on/in. I fear that I will have to render/calculate (the physics for) far too many bodies the way I'm doing it right now. Currently I have 12k bodies in memory at any given time and around 45-60fps. But that's just 3 chunks!

Each block has its sprite attached to it through the box2D body (userData), maybe I should separate them and separate rendering/physics calculation as well? Not sure though, because if a player jumps to another chunk I want him to collide with the blocks there immediately not after a delay (so he is stuck in the middle).

I also tried to calculate the nearest chunk (just go left on the x-axis and down on the y-axis until you find a chunk) and calculate the surrounding ones, but that's much more of a performance hit (logically)

Any ideas/optimizations?

Kindest regards,
Ohuro


texts:
How can I rotate a texture inside a quad without rotating the quad? Here's the code but I'm rotating the whole quad here.

glBindTexture(GL_TEXTURE_2D, texName5);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);

    glPushMatrix();
            glTranslatef(12.8, 10, 10);
            glRotatef(rotateAd, 1, 0, 0);
            glBegin(GL_QUADS);
                    glNormal3f(1, 0, 0);
                    glTexCoord2f(0.0, 0.0); glVertex3f(0, -3,  -3);
                    glTexCoord2f(0.0, 1.0); glVertex3f(0, -3,  3);
                    glTexCoord2f(1.0, 0.0); glVertex3f(0, 3, 3);
                    glTexCoord2f(1.0, 1.0); glVertex3f(0, 3, -3);
            glEnd();
    glPopMatrix();

Thanks.


texts: In Ren'Py, how do I show a different image depending on variables?

texts:
At the start of my RenPy game, the player chooses a male or female character.  The game plays out the same for both, save for some details.

The problem is that I want to write:

show hero normal

and get the image of the correct sex of the character chosen at the start.

I started to write a python function to do this, but it looks wrong because there seems to be enough ATL language to do this, even if I can't find a way.

Any idea?


texts: How does HPA*(Hierarchical Pathfinding A*) really work?

texts:
I'm currently researching for a summary paper on the different variants of A* search algorithm and how they are used in games and I stumbled across the name HPA*. I've heard that it's much more faster than traditional A* but I don't understand it completely. There's hardly any videos or articles written about it so I tried reading a research paper on it and I'm having trouble grasping it. All I can understand is it divides the huge graph in many smaller segments(divide and rule), it creates clusters(subgrids) and precomputes optimal distance between clusters etc..
I would be grateful to any of you if you helped explain it! Thanks in advance.


texts: How to only render whats on screen (Tilemap, Java2D)

texts:
I have some problems with my rendering of a 2Dimensional Map.

for (int col = 0; col <= view.getWidth () / Tile.TILE_SIZE; col ++)
    {
        for (int row = 0; row <= view.getHeight () / Tile.TILE_SIZE; row ++)
        {
            if (checkBounds ((int) topLeftX + col, (int) topLeftY + row))
            {//tiles is an array of Tiles, tiles1 is the mapData
                g.drawImage ((tiles[tiles1[(int) topLeftX + col][(int) topLeftY + row]].getImage ()), col * Tile.TILE_SIZE, row * Tile.TILE_SIZE, null);
            }
        }
    }

But the scrolling of the map is not smooth (tiles move in a TILE_SIZE distance and not with pixelmovement).

Someone has an idea on how to solve this?


texts:
I'm working on my first game, and are looking into the option to save a number of game state settings.

One of the things I want to save is the high scores, this will contain a list of the 10 players that scored the highest.

I have been looking into this for a while, and was wondering what the best way for this is.

While being ingame I will have a list of high scores comprised of Player, Score, Level. This of course needs to be updated each time the score has been beaten, but it also needs to be saved somewhere where it won't be reset the whole time.

I would think this kind of information should be saved into a file (either xml or comma separated values).

The problem I'm facing is what to do on the initial set up (I would like to have some fake values in the high scores table), however if I add that to the file how do I know that the scores in there are the initial set up ones, or the real ones? Once the player has a endgame for the first time, these fake scores should not being shown anymore.

However the player can also reset the scores, and at that point I would like to have the fake scores shown again.

So my question is what is the best way of setting this up? Do I keep 2 files, one with the real scores, other with fake ones? or do I keep the fake ones in a list inside the game and when the file with high scores can't be found I use that list?


texts: Why do mobile games have delays for certain actions?

texts:
Many phone games restrict the number of actions you can take in a given amount of time. I don't get what is the purpose of this limitation. Is it only to force the player to buy additional turns? Some games don't even allow this for some turn "kinds" (like action A can be played again by spending real money while action B cannot be played again by spending money).

Another possible reason would be to limit the bandwidth usage to their server and make it more predictable over time, but I can't see phone games using so much data.


texts:
In my HTML5 canvas game, I need to cross-fade two sprites which have some glow around them. (Glow is backed into sprites.)
Initially, the first sprite is visible. During the cross-fade the first sprite should vanish, and be replaced with the second one. How exactly the cross-fade is done — does not matter, as long as it is smooth and there are no visual glitches.
I've tried two techniques:

During the cross-fade I simultaneously interpolate alpha of the first sprite from 1.0 to 0.0, and alpha of the second sprite — from 0.0 to 1.0.
With this technique I can see background in the middle of the cross-fade. That's because both sprites are semi-transparent most of the time.

During the cross-fade I first interpolate alpha of the second sprite from 0.0 to 1.0 (first sprite alpha is at 1.0), and then interpolate alpha of the first sprite from 1.0 to 0.0.
With this technique background is not seen, but the glow around sprites flashes during the cross-fide — when both sprites are near the full visibility.

In non-HTML5 game I'd use shaders to do cross-fade separately in RGB and alpha channels. Is there a trick to do the cross-fade I need in HTML5 without visual glitches?


texts: How to make 2d map that isnt based on tiles

texts: I am working on a game, and need to make a 2d map that isnt based on tiles. An example of something similar to what I want is all those racing games like "bike race" where the map is just somewhat a line. While I have made tile based 2d games before, both using map editors and programming myself, I have no idea where to begin to make a map type like that. Are there any programs that are used to make such maps? If not, how might I go about it? Just draw the line in an image editor, and program objects to go over that image, and then set up collision detection on the line so that players can't go through it?


texts:
I have code that calculates where the user clicked inside an iso tile in an isometric map. The tile has a width of 1 unit and a height of 0.5 units. My code calculates where they touched inside the tile in these same units. The goal is to then decide where that click falls if you sub-divided the iso tile into a 4x4 grid. The picture below shows how all this is supposed to look.

I have found ascreen co-ordinates to iso formula and it makes sense but for whatever reason, when I try to use it with my data above I get wrong outputs. When clicking from the top corner to the right corner, only the X iso output should change but both the X and the Y change.

I feel like this should be pretty simple but after hours of banging my head against this I can't figure out what I am doing wrong.

Source for screen to iso formula:
How would I translate screen coordinates to Isometric coordinates?

Any help would be greatly appreciated.

float touchedX;
float touchedY;
//below 0.125 represents the tile height because the whole thing
// is 0.5 and its 4 tiles high so 0.125, 0.5 is 2*width which
//is (1 / 4.0) * 2
float gridPointLedftDown = (touchedY / 0.125f) + (touchedX / 0.5f);
float gridPointRightDown = (touchedY / 0.125f) - (touchedX / 0.5f);


texts: What legalese is required in a game installer?

texts: So I've seen a lot of installers, and on almost (if not every one, I don't keep track), all of them, there is a EULA, and specific items that are seen on all installers. However, I'm going to be making my own installer for a game, and I'm wondering if there's certain things that need to be included. Do I need a License Agreement? Should I have a license agreement? Etc.


texts:
I'm trying to texture this asteroid so it looks reasonable.  I'm missing something though.

Following this tutorial, I got this so far.

Now I don't understand the next step: how do you resolve the seam problems?  This icosahedral sphere has a seam running through it that cannot be avoided.  Ok.  How do I paint the texture so it looks seamless when applied to the object?  How do I know which edge connects to what side?  I guess it will just be symmetrical?

This seems awfully hard to texture a simple sphere.  Am I missing some technique here?


texts: Rotating a sprite with Pyglet without changing its X and Y

texts:
I have code which rotates a sprite:

@window.event
def on_key_press(symbol, modifiers):
    print('Rotating')

    global player_sprite

    player_sprite.rotation += 1

    if player_sprite.rotation == 360:
        player_sprite.rotation = 0

However, this rotates the sprite in a manner I don't want: it changes its x and y position. I want it to remain in the same place -- it's a tank, and is not supposed to move when it turns. If, for instance, I do

player_sprite.rotation = 180

it not only faces the opposite direction, but is now far away from its original x and y coordinate.

How would I allow the sprite to rotate without changing its x and y?

Here's a link to my full code.


texts: How to render images/textures in shape/polygon form?

texts:
I'm working with SFML right now, and upon finishing the tutorials I still do not know how to give a shape a texture or image -- not just a solid color/outline.

The only thing I know can take an image is a sprite, but thats way to simple, as it only allows you to render rectangular images in a rectangluar way!

What are the techniques for rendering images onto shapes, and only inside the shape? It would be great if some of you could provide some resources or SFML-specific stuff!


texts: sf::RectangleShape's position is not same as I set it to

texts:
When I try to print my box.getSfShape()'s position it does not print out the position I set it to have.

( The box.getSfShape()'s position is by default set to 0 )

Wrong output : ( printing the position of the box.getSfShape() )

( prints out : X : 0 Y : 0 ((These are the default assigned positions)) )

box.getSfShape().setPosition(box.getBody()->GetPosition().x / b2Meter, box.getBody()->GetPosition().y / b2Meter);

But when I print out the calculation only :

std::cout << "X : " << box.getSfShape().getPosition().x << " Y : " << box.getSfShape().getPosition().y << std::endl;

It prints out a increasing Y value and a X value on 0 like it should do.

So, I'm guessing the call to set the box.getSfShape() position somehow fails.

If you need something more, please tell me what to add :)


texts: In unity 5 export package is not working correctly

texts:
I am using unity 5. I Created an objects with layer names. I tried to export a package. After Exporting, i import the package in new project and ran the project its not working. observed that objects layer name is missing for all the objects. i attached the screenshot with this.

Before Export :

After Import the Exported Package :

In layer drop down box no layer name was found. only the default layer name is available. if anyone knows the answer please tell me.


texts: MoCap data files applied to avatars using Mecanim

texts:
I am applying some animations (e.g. running) from this free MoCap package that I got off the Unity Assets Store, and as far as I can see from running the animation previews, they seem fine (i.e. playing smoothly) but once I apply them to my avatar (generated through the free AutoDeskCharacterGenerator) and I run the animation, the avatar seems to rise on the floor...

Please see the attached images that illustrate the character (with its collider, etc...) initially being perfectly aligned (touching the ground) but then a few seconds into running, it has been lifted off the ground.

At first, I thought this must be due to the recorded motion data files, but (1) it has happened in every animation I have tried from the package so far, and (2) these motion data files were recorded off real people, so I find it unlikely that all the performers happened to be moving around on very uneven surfaces and slopes.

Has anybody come across this problem before?


texts: OpenGL 3.3: render to framebuffer w/o depth attachment

texts:
I want to render my scene to a framebuffer and store the RGBA values in a texture. For this, I attach a texture to GL_COLOR_ATTACHMENT0. When I define a GL_DEPTH_ATTACHMENT texture as well, everything is rendered with the correct depth. However, if I leave out the depth attachment (because I don't need it in a later stage), wrong depth values are output, if I further use the RGBA texture (e.g. when blitting the framebuffer to another one).

Is this correct behavior, i.e. do I always need to specify a depth attachment?

edit: wrong depth values: By attaching a GL_COLOR_ATTACHMENT0, a color texture (e.g. RGBA) is output. Without a depth attachment, the colors are at the wrong "depth", in the sense that the pixels of an object behind a wall are rendered, although the corresponding pixels of the wall should be rendered instead.

Regards,
bobbel


texts: Phong lighting - there is something very strange with specular lighting

texts:
I implemented Phong lighting. Everything seems to work - torus and spheres are lighted as expected, etc. But I notices something strange regarding specular lighting of directional light.

Here are two screenshots.

First:

Second:

As you can see more area has specular lighting when camera is far from an object.

Here are simplified vertex shader:

#version 330 core

layout(location = 0) in vec3 vertexPos;
layout(location = 1) in vec3 vertexNorm;
layout(location = 2) in vec2 vertexUV;

uniform mat4 MVP;
uniform mat4 M;

out vec2 fragmentUV;
out vec3 fragmentNormal;
out vec3 fragmentPos;

void main() {
  fragmentUV = vertexUV;
  fragmentNormal = (M * vec4(vertexNorm, 0)).xyz;
  fragmentPos = (M * vec4(vertexPos, 1)).xyz;

  gl_Position = MVP * vec4(vertexPos, 1);
}

... and fragment shader:

#version 330 core

in vec2 fragmentUV;
in vec3 fragmentNormal;
in vec3 fragmentPos;

struct DirectionalLight {
  vec3 Color;
  vec3 Direction;
  float AmbientIntensity;
  float DiffuseIntensity;
};

uniform sampler2D textureSampler;
uniform vec3 cameraPos;
uniform float materialSpecularFactor;
uniform float materialSpecularIntensity;
uniform DirectionalLight directionalLight;

out vec4 color;

void main() {
  vec3 normal = normalize(fragmentNormal); // should be normalized after interpolation

  vec4 ambientColor = vec4(directionalLight.Color, 1) * directionalLight.AmbientIntensity;

  float diffuseFactor = clamp(dot(normal, -directionalLight.Direction), 0, 1);
  vec4 diffuseColor = vec4(directionalLight.Color, 1) * directionalLight.DiffuseIntensity * diffuseFactor;

  vec3 vertexToCamera = normalize(cameraPos - fragmentPos);
  vec3 lightReflect = normalize(reflect(directionalLight.Direction, normal));
  float specularFactor = pow(clamp(dot(vertexToCamera, lightReflect), 0, 1), materialSpecularFactor);
  vec4 specularColor = vec4(directionalLight.Color, 1) * materialSpecularIntensity * specularFactor;

  color = texture(textureSampler, fragmentUV) * (ambientColor + diffuseColor + specularColor);
}

Full source code without any simplification could be found in this repository.

I wanted to know if I implemented something wrong. Or is it OK for Phong lighting?


texts:
I'm making a lighting system right now, and the last part I have to do is to invert the alpha channel on the final light map. My previous code that used to work was

DataBufferByte buf = (DataBufferByte)lightmap.getRaster().getDataBuffer();
    byte[] values = buf.getData();
    for(int i = 0; i < values.length; i += 4) values[i] = (byte)(values[i] ^ 0xff);

But this code threw this "java.lang.ClassCastException: java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte" on the first line. So, I changed it to

DataBufferInt buf = (DataBufferInt)lightmap.getRaster().getDataBuffer();
    int[] values = buf.getData();
    for(int i = 0; i < values.length; i += 4) values[i] = (int)(values[i] ^ 0xff);

but this doesn't actually invert the alpha, but seems to invert the color between the hue and black? I know that this works

for(int i = 0; i < lightmap.getWidth(); i++) {
        for(int j = 0; j < lightmap.getHeight(); j++) {
            lightmap.setRGB(i,j,(lightmap.getRGB(i, j) ^ 0xFF000000));
        }
    }

But testing this, it brings my framerate down to 15 fps.

So I guess my question is this: Either how can I fix this, or is there a fast way to invert the alpha values of a bufferedimage?


texts: How to iterate over 25 Sprite Objects (Unity 5 - C#)

texts:
I wanna show a minimap on the screen. The minimap would look like this (bottom right corner, this was done time ago in Visual Studio):

Have two problems with that, I have 25 Image objects created in the scene and 25 in the playercontroller script:

public Image minimap0, minimap1, minimap2, minimap3, ... , minimap24;

but I can't make to change its sprite, and also, I don't know how to change all 25 objects sprite with a "for" loop (the foor will look like this http://imgur.com/qfi1Ht1 ).

The map is stored in an array for checking positions.


texts: Finding the shorter turning direction towards a target

texts:
I'm trying to implement a type of movement where the object gradually faces the target. The problem I've run into is figuring out which turning direction is faster. The following code works until the object's orientation crosses the -PI or PI threshold, at which point it will start turning into the opposite direction

void moveToPoint(sf::Vector2f destination) {
    if (destination == position) return;

    auto distance = distanceBetweenPoints(position, destination);
    auto direction = angleBetweenPoints(position, destination);

    /// Decides whether incrementing or decrementing orientation is faster
    /// the next line is the problem
    if (atan2(sin(direction - rotation), cos(direction - rotation)) > 0 ) {
        /// Increment rotation
        rotation += rotation_speed;
    } else {
        /// Decrement rotation
        rotation -= rotation_speed;
    }

    if (distance < movement_speed) {
        position = destination;
    } else {
        position.x = position.x + movement_speed*cos(rotation);
        position.y = position.y + movement_speed*sin(rotation);
    }
    updateGraphics();
}

'rotation' and 'rotation_speed' are implemented as custom data type for radians which cannot have values lower than -PI and greater than PI. Any excess or deficit "wraps around". For example, -3.2 becomes ~3.08.


texts: Creating a Static function inside my class to handle small housekeeping tasks

texts:
I have used Unity 3D for quite some time, and a lot of my game programming experience originates from using UnityEngine.

Writing in XNA, I am setting up a nested list of objects. Each object will be an instance of a class, GameObject. At the point of creation, I will have to perform some administration on each element, to sort through them and allow correct operation.

My understanding is that if I have the administration function inside the class, each instance will contain the instructions to perform the task, effectively having N times the same instructions. I have seen some functions instead use the static identifier, in UnityEngine. My understanding is that each instance will instead reference the same copy of the instructions, tidying everything up a bit better.

From what research I have done, all I can find supports that creating static functions inside instantiated instances of a class is impossible. However, I have functions inside UnityEngine that are static, and linked to instantiated copy's of a single class.

My question is: How do I contain a static function inside my class, to perform routine administration function? I am wanting it to be able to crunch numbers derived from the instance calling it, in order to set up other fields within the instance. Would I have to send a ref type of that field, to ensure I am editing the exact instance of it, or do I have a keyword that automatically points to the instance calling the function?


texts: Steelseries Stratus XL controller: Keycode for middle button

texts:
I'm working on an Android app (Java, level 19+) that uses a controller to e.g. walk and it's working (almost) fine with both the Steelseries Stratus XL and the Moga Pro Power. The only problem is that the Stratus XL has a button in the middle (the one with the circle: click) that closes the app.

I now want to disable that but I have no idea what the keycode for the button is and it also doesn't say anything about it on the official Steelseries homepage.

Has anyone here worked with the Stratus XL before and knows what keycode to use?


texts:
I'm really trying to up my game in game mathematics and now I'm working on enemy movement and a bit of AI. I have an enemy with two modes attack and avoid, based on an integer avoid variable that's either 1 or 0.

On avoid I want it to hover by the player, moving back and forth at a distance until it is set to avoid.

On attack I want to go close at a steady pace say an x and y velocity of 12, then once it reaches a certain distance to gain speed.

I have disx and disy variables that have the distance from each other for each coordinate. I also have a totDis variable with the normal a^2 + b^2 = c^2 formula. I'm pretty sure I'll need another variable that I'll have to change depending on the distance that effects the speed.

It kinda feels like I have all the pieces to the puzzle, I just don't know how to put them together though lol.

I'd like to be able to do this as mathematically as possible and I don't want anyone to give the the answer or do it for me. I was hoping if anyone could give me pointers or tips or just ideas on the directions I can go myself because I really want to have an understanding of this. I hope this is specific enough, if not I'll try to edit my question for you.


texts: Are there still advantages to using gl_quads?

texts:
OK, I understand that gl_quads are deprecated, and thus we're not 'supposed' to use them anymore. I also understand that a modern PC when running a game using gl_quads is actually drawing two triangles.

Now, I've heard because of that a game should be written using triangles instead. But I'm wondering if, due to the specifics of how OpenGL makes that quad into two triangles, it is ever advantageous to use quads still?

Specifically, I'm currently rendering many unconnected quads from rather large buffer objects. One of the areas I have to be careful is how large the vector of floats I'm using to make/update these buffer objects get (I have quite a few extra float values per vertex, and a lot of vertices in a buffer - the largest buffers are about 500KB).

So it strikes me that if I change my buffer objects to draw triangles this vertex data is going to be 50% larger (six vertices to draw a square rather than 4), and take 50% longer for the CPU to generate.

If gl_quads still work, am I getting a benefit here, or is the 50% extra memory and CPU time still being used on OpenGL's automatic conversion to two triangles?


texts: Which should be faster: 10 flat shaded polygons or 2 with a transparent texture

texts: I have particle system, and I want to the individual particles to take the shape of a star.  Which should be faster: Drawing the 10 polygons using a flat shader, or 2 polygons (a square) with a partially transparent texture?


texts: Should I use secure WebSockets for a game?

texts:
Is SSL necessary for a web game? I'm using Node.js with socket.io.

Without it, when using unsecured networks someone on the LAN could change commands being sent to the server and "take over" a player. But this could only happen on unsecured shared networks, so it doesn't sound too bad. Or is it?

And lets ignore the authentication phase for a moment and assume this part is secured, are there any other reasons why I should use SSL on the sockets?


texts: RigidBody or Character Controller for Zero Gravity first person shooter

texts: I am developing a single person, first-person shooter that takes place in space. I want to be able to simulate zero gravity. Should I use a Rigid-Body or a Character Controller?


texts: 2D Side-scrolling Strategy Game Pathfinding Help

texts:
Hey Guys,I am trying to implement dungeons into my 2d RTS ish game.The dungeons is made out of rooms, you start at the top, and you can unlock rooms with scouts.The picture is the unlocked version of the dungeons, except for the middle part where it says "locked".For example the long rooms in the picture are actually consists of 3-4 rooms.
The dungeon is handbuilt by me, there are no obstacles except for unlocked areas and walls.No need for collision avoidance.The boxes with up and down indicates "ladders", when a unit wants to go up/down it just fades out and fades in the new layer, no moving up/down animation.You control the units by mouse.No jump mechanic etc, they just move flat on the green areas.

So I think I need to calculate and store which ladders(or nodes) the unit needs to take to reach the target, I need to check if ladders are connected to each other I think.But I don't know, not a great programmer.I have looked into Astar and dijkstra's algorithms but they seem complicated to implement, there is a built in Astar in gamemaker but it uses grid system and doesn't seem to fit to my problem.
Do I really need to learn one of those algorithms or can I get away with a simpler approach?Any pseudo code you guide me with?I would really appreciate the help.I know a bit of c# and unity.Thanks a lot!


texts: Rate-limiting players actions in a multiplayer game

texts:
I'm thinking about building a multiplayer game with combat between players and monsters. Actors need to have a maximum actions per minute, otherwise users could cheat by holding down the attack key. Plus, I'd like to vary the maximum APM depending on the player class and monster.

How should I handle rate limiting combat in my game?

Assuming every actor has a timestamp of when their last action occurred, should I queue up actions to execute or should I drop them if they're received too early? Can you think of any reading material or examples I could research?


texts:
After asking a similar question yesterday I've come across another problem with using joints in box2D / LOVE and trying to create a weighted chain.

Everything is set up as follows, I've tried to remove most of the fluff:

Each link is created as a body/shape pair then joined together and added to a links table.

    for i = 1, segments, 1 do

        link = {}

        link.body = love.physics.newBody(world, xpos, ypos, "dynamic")

        if (i == segments) then
            link.shape = love.physics.newCircleShape(endlink_radius) --Ending link
        else
            link.shape = love.physics.newCircleShape(link_radius)
        end

        link.fixture = love.physics.newFixture(link.body, link.shape) --Fix bodies to shapes

        table.insert(links,link)

        ypos = ypos + link_distance

    end

Links are joined together using rope joints to allow for some springy-ness:

    for i = 2, #links, 1 do

        x1,y1 = links[i-1].body:getPosition()
        x2,y2 = links[i].body:getPosition()
        links[i-1].join = love.physics.newRopeJoint(links[i-1].body, links[i].body, x1, y1, x2, y2, link_distance, true )

    end

The player controls the first element of the chain and holds the table of links, its created as follows:

local body = love.physics.newBody(world, 300, 100, "kinematic")
local shape = love.physics.newCircleShape(3)
local fixture = love.physics.newFixture(body, shape)
local chain = _chain.new(world)

Joined to the chain:

x1,y1 = body:getPosition()
x2,y2 = links[1].body:getPosition()
join = love.physics.newRevoluteJoint(body, links[1].body, x1, y1, x2, y2, true )

The player tracks the mouse cursor, determines a velocity and moves towards it by setting the linear velocity of the first chain element:

    body:setLinearVelocity(velocity.x, velocity.y)

And this very nearly works, you can pull the chain around quite nicely using the mouse (directing the top pink element), however if you keep spinning the chain it begins to stretch and pull away from the first element:

Any ideas on how to solve this?

I've tried using different joints and parameters, adding a reinforcing joint from the first link to the last, adjusting body weights and altering the update iterations but can't seem to find anything effective.

Many thanks.


texts: what do you choose to point player in multiplayer game coding?

texts:
I'm making C or C++ texture multiplayer game (monopoly) and
to code multiplayer, defined type user
when you change player or point player in main() or other()
you choose Number or pointer?
for example, when one turn finish how do you change player
like user++ (user is int) or use changeUser() ...
i'm newby and know nothing


texts:
I've made the collision box for my player (and other blocks) and I'm now testing gravity and collision on the player. What I saw was that my collisionbox is updating slower than my player is moving.

It's not visual if he's just moving, but you can clearly see it when he's falling at a certain speed. (and it causes problems with the collision because the box updates slower)

This is for updating my collision box (and player):

public override void Update(GameTime gameTime, Rectangle clientBounds)
{
    // collision box for player
    if (left)
    {
        collisionRect = new Rectangle((int)position.X + 10, (int)position.Y + 14, frameSize.X + 2, frameSize.Y + 20);
    }
    else
    {
        collisionRect = new Rectangle((int)position.X + 8, (int)position.Y + 14, frameSize.X + 2, frameSize.Y + 20);
    }
    // for player
    position += direction
}

This is for updating my player:

public override Vector2 direction
{
    get
    {
        Vector2 inputDirection = Vector2.Zero;
        keyboard = Keyboard.GetState();

        if ((keyboard.IsKeyDown(Keys.Left)) || (keyboard.IsKeyDown(Keys.A)))
        {
            moving = true;
            walking = true;
            inputDirection.X -= 1;
            running = false;
            left = true;

            if (keyboard.IsKeyDown(Keys.LeftShift))
            {
                speed = speedMultiplier;
                inputDirection.X -= 1;
                running = true;
            }
        }

        if ((keyboard.IsKeyDown(Keys.Right)) || (keyboard.IsKeyDown(Keys.D)))
        {
            moving = true;
            walking = true;
            inputDirection.X += 1;
            running = false;
            left = false;

            if (keyboard.IsKeyDown(Keys.LeftShift))
            {
                speed = speedMultiplier;
                inputDirection.X += 1;
                running = true;
            }
        }

        if (!(keyboard.IsKeyDown(Keys.Right)) && !(keyboard.IsKeyDown(Keys.D)) && !(keyboard.IsKeyDown(Keys.Left)) && !(keyboard.IsKeyDown(Keys.A)))
        {
            moving = false;
            walking = false;
        }

        if (stopping)
        {
            inputDirection.X = 0;
        }

        if (falling)
        {
            inputDirection.Y += 1f;

        } else
        {
            inputDirection.Y = 0;
        }

        return inputDirection * speed;

    }
}

Or do I also need to use a get; for my collisionbox instead of updating it in Update()?


texts:
My Journey...

I've long struggled with rectangle to rectangle collision resolution. I've been making games for almost 10 years and still have yet to find a foolproof, reliable strategy.

When doing research on 2d, rectangle to rectangle collision resolution, I find myself digging through piles of collision detection, or other topics that have nothing to do with my search for truth (circle to rectangle, other detection methods...)  For me, detecting collision has never been the issue...

if player.x + player.width > box.x and
   player.x < box.x + box.width and
   player.y + player.height > box.y and
   player.y < box.y + box.height then
     // A collision has been detected...
     // But now I am lost.....

Assuming both the player and box objects are positioned at their upper left corner

The Rectangular Paradox...

For those brave enough, there is the path of chaos, torture, and unknown horrors available... The road known as "creating your own". I have chosen to walk this path many times, never to find the answers I'm looking for. I'm sure I share some quarrels of this road with fellow developers.

At first you might think it a simple task: "Once you know the rectangles are overlapping, how difficult can it really be to push one out of the other?" Oh boy, how I miss that sweet innocence...

Let us say, the player in the above example is falling down on top of the box, and we want it to stop and be pushed back to the top of the box. Easy, right? We can just do a simple check if the player is above the box, and if so, push him up to the top.

// We know the player is overlapping with the box..
if player.y < box.y then
  player.y = box.y - player.height

Done. Tested and proven to work. But, let's say now we want the player to stop at the left side of the box as well..

if player.x < box.x then
  player.x = box.x - player.width

Looks like it should work fine right? But no. Upon testing you move the player to collide with the left side of the box, and bam. Suddenly, he has immediately moved to the top of the box.

Why? The player can be both above the box, and to the left of the box at the same time. So one seems to end up always being favored over the others. To mitigate this I have written 3 nested if statements, 50 line chunks of code for each side of the rectangle, and wasted near weeks of my life..

Conclusion

Although I walk my journey alone - I know there are others, battling the same demonic mystery of rectangle to rectangle collision resolution. And also.. Those who have conquered it...

I'm hoping someone can help me understand their solidified, proven methods of resolution. To help me and any other developers reading this right now, become level 100 devs.

I made a codepen for anyone who is interested to use as a playground for showcasing resolution methods.


texts:
I've written a code that allows me to talk with an NPC. This works as long as there is only 1 NPC on the map. I'll explain why.

public void getNPCCollision(){
    for (int i = players.size() - 1; i >= 0; i--) {
        Player player = players.get(i);
        for (int j = beings.size() - 1; j >= 0; j--) {
            Being being = beings.get(j);
            if(player.getBounds().overlaps(being.getBounds())) {
                setX(oldX);
                velocity.x = 0;
                setY(oldY);
                velocity.y = 0;
            }
            else if(player.getBounds().overlaps(being.getTalkingBounds())) {
                canTalk = true;
                talkAbleBeing = being;
            }
            else{
                talkAbleBeing = null;
                canTalk = false;
            }
        }
    }
}

I check every update if my Player walks into an NPC's Talking Rectangle. It goes by every NPC on the map. The thing is If I'm not on NPC 1's rectangle but on NPC 2's rectangle, It'll still set canTalk to False because I'm indeed not in his rectangle.

Is there any way I can fix this issue? Please, any help appreciated.


texts: How do I know if I'm abstracting graphics APIs too tightly?

texts:
When making a renderer that supports multiple graphics APIs, you would typically want to abstract your code in some sort of low level library that is tied with some graphics API like OpenGL,  Vulkan, D3D11 and so on;

They work very differently from each other, so making a good generic API becomes essential;
I've read that you would typically want to use a "back-end" that implements the basic functionality for each API you want to support, and a "front-end" which is what is used by the programmer to draw stuff on the screen.

How do I know if I'm making too much of a tight abstraction?


texts: How can I improve the display of my png files?

texts:
I develop a mini Android game available from my github (also the release apk file). The game is for kids and you are supposed to catch falling object and get points for that. Now I just created png files for the sprites and added alpha channel in gimp. It looks better, before alpha channel:

After:

But I'm not 100 % satisfied with the rough edges of the sprites. Am I correct that if I do the alpha channel more exact then the sprites will look even better (without the edges) or is there some other mistake that I make with the sprites?

Edit: With new background image, it looks like this.

Edit 2: I used jamie the monkey now of BSD license which renders better. It seems to be more exact work in GIMP that is needed.

Edit 3. Now I am satisfied. Thanks.


texts: Trying to Access Components of an Object in another class

texts:
I think my C# is a bit lacking here but I am trying to access a component in a list of objects in another class. I am trying to access UnitController from MultiSelectClient and I'm not sure how to do this. I can remove the objects from the list but I can't seem the access each one even if I try a ForEach loop, I can't wrap my head around it.

UnitController.SelectedUnits //Is the list I'm trying to access.

Ive tried doing

UnitController.SelectedUnits.Find/FindAll(gameObject)//but that returns an error

This is where the list is defined

public class UnitController: MonoBehaviour
{
    bool clicked = false;
    bool dragging = false;
    //public float speed = 10f;
    //public float rotationSpeed = 10f;

    public LayerMask groundLayer;
    public NavMeshAgent playerAgent;

    public static Vector3 mouseDownPoint;
    public static Vector3 mouseUpPoint;
    public static Vector3 currentMousePoint;

    public static Rect selection = new Rect(0, 0, 0, 0);
    private Vector3 startClick = -Vector3.one;
    public Texture2D selectionHighLight;

    public static List<GameObject> SelectedUnits;

    public RaycastHit firstRay;
    public RaycastHit secondRay;

    private void Start()
    {
        SelectedUnits = new List<GameObject>();
    }

This is the script that needs to access it. At least I want to be able to iterate through the list and access each unit in the list and its components.

public class MultiSelectClient : MonoBehaviour
{
    public bool Selected = false;
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
            camPos.y = Screen.height - camPos.y;

            //if inside the cameras drag selection area then mark player as selected
            Selected = UnitController.selection.Contains(camPos);

            Debug.Log("Selected");
            if (Selected)
            {
                addTo();
            }
            else
            {
                UnitController.SelectedUnits.//something
                UnitController.SelectedUnits.Remove(gameObject);

            }
        }

    }
```


texts:
In Phaser, I am loading a Tilemap from JSON.

I would like my Tilemap to display in a particular position (for simplicity here I say the middle of the screen).

var map = this.game.add.tilemap('level');
map.addTilesetImage('tiles2', 'tiles2');
var layer = map.createLayer('Ground', map.widthInPixels, map.heightInPixels);
layer.anchor.set(0.5);

//this does not work...
layer.position.set(this.world.centerX, this.world.centerY);

//or even
layer.x = this.world.centerX;
layer.y = this.world.centerY;

The anchor.set works as it should however setting the position does not seem to work.

What am I doing wrong?


texts: Where does the Game class come from in the DrawableGameComponent constructor?

texts:
I'm making a project to Windows Phone using Silverlight + XNA, but I don't know how I can use the DrawableGameComponent because the constructor requires a Game class, it looks like this:

Planet.cs

class Planet : DrawableGameComponent
{
    public Planet(Game game): base(game){

    {
}

but in my first page of Silverlight and XNA project not is a Game class it's this:

GamePage.xaml.cs

public partial class GamePage : PhoneApplicationPage
{
   ...
}

Where do I find the Game class to pass into the DrawableGameComponent constructor?


texts:
I am building a Pong clone to learn interactive programming and I've stumbled in getting the ball movement and bouncing on the paddles right.

If I play the original game I can't really understand how the "spin" and the paddle bounce works.

I've been searching a bit on the internet and all I got was just more confusion.

Can anybody explain me how the bounce is handled?
If the paddle stands perfectly still and the ball, just moving on x, hits the paddle at the center I simply get -x, that is clear.

What happens if you hit the paddle on the sides?
What changes if when the ball hits the paddle the paddle is also moving?

I did an Arkanoid-like implementation but it is far from the real Pong feeling.


texts:
To have better texture2D quality in my 2D game, I had to recreate every textures with 300% of their original size.
But the lights have to bright 3 times more.

For lights, I'm using this : Catalin's blog

I have to render some lights, but with only 1 with 800 pixels of radius, my game works with around 15fps or less.
And if I improve the light quality, I have an issue with the (gpu ?) memory.

How must I do to render a light with 800 pixels of radius without this gpu cost ?
Should I use another effect ? Do you have some to suggest ?
(example : Andrew Russell's game : "Dark" has a lots of big lights, and the game works perfectly)
Hope you can help.


texts:
I'm having a problem with the Farseer Physics Engine, where in a tiled environment, my object will at times interact with corners of others objects, even if they align perfectly.

I've read about people suggesting that you calculate and create one larger object, using Marching Squares or something similar. This is not an option however, as I'd like each tile to have different physical qualities, like different friction and restitution.

My question is, what exactly is causing it, is it float precision issues or something else? And is there a way to fix it, without breaking the whole physics engine?


texts: No intellisense with with Unity 5.5, Visual Studio Code integration, OSX 10.12.1

texts: I get this with the listed software. It doesn't recognize object types and I can't use reference-finding. I have the Omnisharp plugin installed and updated. Just wondering if this is supposed to work properly yet. I'm opening it with Assets->Open Project In Code.


texts: How can I move a created Image in Slick2D?

texts:
I want a image to follow the mouse, and I use Image class of Slick 2D:

public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    mouseImage = new Image("res/mouse.png");
}
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics  graphics) throws SlickException {
    mouseImage.draw(0,0,0.1f);
}

But it seems that it does not have method for re-positioning a Image object. So how can I implement it (in update method)? Thanks.


texts: How can I reduce the size of bundled Unity DLLs on Android?

texts:
I have created a simple project (I am a Unity beginner) for Android but the apk size is around 18 MB!

I checked the documentation. One way to decrease the apk size is to check the editor log. Then I discovered that imported DLLs have a size of 3.9MB.

I only used UnityEngine and Collision packages. So how can I avoid to import the other big DLLs?


texts: Correct order of tasks in each frame for a Physics simulation

texts:
I'm playing a bit around with 2D physics. I created now some physic blocks which should collide with each other. This works fine "mostly" but sometimes one of the blocks does not react to a collision and i think that's because of my order of tasks done in each frame.

At the moment it looks something like this:

function GameFrame(){
    foreach physicObject do
        AddVelocityToPosition();

        DoCollisionStuff();      // Only for this object not to forget!

        AddGravitationToVelocity();
    end

    RedrawScene();
}

Is this the correct order of tasks in each frame?


texts: Why can't CreateEvent be used as a value in a blueprint Map?

texts:
I need to map Button to Event, seeing as Unreal does not allow me to call premade events (in this situation, OnHovered for Buttons)

When you connect a CreateEvent to something like a Timer, you have the option to choose a delegate, as shown:

However, when you connect this to the value in a Map, you do not get to choose, despite the connection being allowed.

Tl;Dr:

Why can I not use event delegates as a value in a pair map?


texts: Fresh Unity/Visual Studio 2017 install error

texts:
Installed Unity 5.6.3p2 (my projects's current version) on a new machine. When I opened the project in Visual Studio 2017 I got a prompt to update the .NET framework from 3.5 to (I think) 4.2.x. I confirmed the upgrade for all projects in the solution but now all I get is this

If I close and reopen visual studio I no longer get the upgrade prompt. I tried downloading .NET 3.5 to no avail. Any information is appreciated.


texts: Where to start the coding of online leaderboards?

texts:
I NEVER, EVER did ANY sort of network code in C++, I don't know even the libraries that exist, but a popular demand for my game is online leaderboards...

So, what sort of libraries I should research into?

My game is multiplatform (win, gnu, mac), uses C++, ClanLib 1.0 and Lua. Also the engine is zlib (so proprietary stuff that I cannot release source don't work)


texts: How would I go about serializing my LibGDX game?

texts:
I am currently using Kryo for serialization. I have a Player class, but it extends Sprite. Sprite isn't serializable. This means I can't serialize Player as a whole. Is there another way to do this? Or should I make a separate class for every object that needs to be saved, and manage all the data that needs to be saved in there?

This is my first game and I'm going for a top-down (like pokémon) RPG game. I also need to save locations of monsters and animals in certain maps etc. So I'm not sure if this would be the right way to go about it? I can't find that much about this topic for games and kryo in specific online, so hopefully someone can enlighten me a bit.


texts:
I've recently started making a 2D game, and I want to implement an atmosphere.

My plan is to include many in-game compartments, such as tubes and ventilation. If I open an airlock from a room with zero pressure to a room with high pressure, I should feel a heavy knock back. If I mix gases in a room, and players both human and alike would not be able to breath, they would die.

I have idea of how to do it, but it won't be that sufficient and real. I don't need an real atmosphere; it just needs to feel real.

This is the small list of what I want to implement:

Gas pressure that effects the environment, such as moving objects and causing damage to objects.
Simple gas mixing, where I would like to implement 4-5 different gasses.
Some sort of in-game device to affect atmosphere and check its state.

How would I go about programming atmosphere for a game?


texts: How to 3 triangle could generate hundred of fragments?

texts:
I am just watching the Shaders intro video from here where the Youtube is saying

3 vertices make up a triangle and Could generate a couple hundred fragments based on how much of the screen that triangle occupies

Its super easy to understand the first thing but the next thing fragment? What actually the fragment is? When we join the three vertices the face will appear which is called a fragment? then how 3 vertices colud generate hundred of fragments?


texts: Rigidbody physics concept: Why translate collision shape on-the-fly instead of mutating it?

texts:
Crossposting at https://stackoverflow.com/questions/29993547/rigidbody-physics-concept-why-translate-collision-shape-on-the-fly-instead-of-m

I've spent some time going through physics engine's sourcecode in Java like JBox2D, Phys2D (both 2D) and JBullet (3D).

I observed that, while the rigid bodies move and are mutated in each step, the collision shapes that are attached to them, are not. Instead, they always stay located around the coordinate origin. When checking two rigidbodies for collisions, a "translation" object is fetched from each and is used to translate the two checked shape's vertices (or other defining properties, depending on the shape type) to their attachment's world position on-the-fly. These information are then used to detect collisions and react to them.

I've concluded the main purpose is, that you can reuse the same shape instance for multiple bodies, as they are stateless in the described scenario and save some memory as the needed information are calculated on-the-fly in each step.

However, I currently see more advantage in mutating the shape's positional properties as in their member values. Each shape's aabb and vertices would change ONE TIME in each step, so you don't need to calculate the same vertices multiple times when intersecting one shape to multiple other ones. Plus, you could also change areal properties (damage deformation) of the shape, because it is only used by one body.

So the questions is:

Why is it common to use positionally immutable collision shapes instead of mutable ones?

Edit:
Found quite the same question, but without much of an answer at Storing rigid body collision shapes in local or world coordinates


texts: LibGDX player movement on X axis is very limited

texts:
I'm making a side-scroller game using LibGDX, where player can move only on X axis. The problem is that the player can only move on positive X value, so he can't go to negative X. This is not that big of a problem, but the main problem is that where-ever I choose his initial position, he will never move right, so he basically can't extend his initial X value. I'm making movement with Gdx.graphics.getDeltaTime(), but when I don't use it, strangely everything works right. Other things work alright, the animation change works, test outputs worked, the problem always occurs only in the part of adding delta time to the x axis.

Player's initial position:

private Actor hiro;
hiro = new Hiro("Hiro", 106, 4, 32, 32);

(I'm not using LibGDX's Actor class, I made my own which uses animations)

Player's constructor:

public Hiro(String name, int x, int y, int width, int height) {
    super(name, x, y, width, height);
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    standingRightTexture = new Texture("hiro_standing_right.png");
    standingLeftTexture = new Texture("hiro_standing_left.png");
    walkingRightTexture = new Texture("hiro_walking_right.png");
    walkingLeftTexture = new Texture("hiro_walking_left.png");
    standingRight = new Animation(standingRightTexture, 1, 10f, true);
    standingLeft = new Animation(standingLeftTexture, 1, 10f, true);
    walkingRight = new Animation(walkingRightTexture, 8, 0.6f, true);
    walkingLeft = new Animation(walkingLeftTexture, 8, 0.6f, true);
    setAnimation(standingRight);
    state = State.STANDING_RIGHT;
    facingRight = true;
}

Player's movement:

if(Gdx.input.isKeyPressed(Input.Keys.D)){
        x += Gdx.graphics.getDeltaTime() * 6f;
        facingRight = true;
        state = State.WALKING_RIGHT;
        System.out.println(x);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.A)){
        x -= Gdx.graphics.getDeltaTime() * 6f;
        facingRight = false;
        state = State.WALKING_LEFT;
        System.out.println(x);
    }

Playing Screen's render method:

@Override
public void render(SpriteBatch spriteBatch) {
    cam.update();
    spriteBatch.setProjectionMatrix(cam.combined);
    spriteBatch.begin();
    hiro.getAnimation().update(Gdx.graphics.getDeltaTime());
    spriteBatch.draw(hiro.getAnimation().getFrame(), hiro.getX(), hiro.getY());
    moveCamera();
    spriteBatch.end();
}

If you want other segments of code, I'll provide it.

I greatly thank everyone whiling to help.

Edit: SOLVED! All I had to do was to use float axis instead of integer. Silly me!


texts: How can i stop Steam's RPG Maker XP from rewriting my Game.ini file?

texts:
I've been using RPG Maker XP for a long time, i think before Steam. back then to get RPG Maker XP Working you had to connect it to the net to get an Ntitles serial before you could put in the activation code.

this has been fine for the past 10-15 years where i have been running it off my Portable HDD with my projects (on Windows XP and 7). i also have gotten RPG Maker XP on Steam with a Humble Bundle that included VX, VX Ace and MV. recently i upgraded my PC now with Windows 10 and when i went to use my old copy on my Portable HDD, even when connected to the internet (and i did check the network, nothing was wrong) it couldn't get the Ntitles serial. so then i fell back to the Steam Version. this worked and didn't even ask me for a key (though downside is that i now have to have Steam running for when it starts up).

While working on my project i went to playtest and i got the error

  The specified procedure could not be found

after debugging i found out that when i saved my Project, the Steam RPG Maker XP dumped a RGSS104E.dll file into my project and rewrite Game.ini to point to it. this is an issue because i use the RPG Maker XP Ace which required VX Ace's RGSS3 .dll. when i edited the .ini file my game worked with no issue and i found that if i save Game.ini with the correct library after saving my project before pressing the playtest button things work.

however keeping Notepad++ open and re-saving the file each time is a pain. ways to avoid this that i have tried are

Rename the RGSS3 .dll in my project folder to RGSS104E.dll - doesn't work as RPG Maker XP is dumping RGSS104E.dll overtop (confrimed as the Modified Date changes and the error returns)
Replace RGSS104E.dll to a renamed RGSS3 .dll in the RPG Maker XP Install Dir - doesn't work because then the Editor reports that it couldn't find RGSSInitialize
Do above but after the editor has started - the .dll is locked and Windows wont let me do anything with the .dll
Use my original copy of RPG Maker XP - the Ntitles server i suspect is dead as it wit keeps reporting the same issue while while Steam's version is installed all Projects associate with it (as such uninstalling Steam's version wont work)

So I would like to know how can i stop Steam's RPG Maker XP from rewriting my Game.ini file? if i stop it doing this then i can point to the RGSS3 .dll and just not care when it redumps RGSS104E.dll. alternatively i would like to stop RPG Maker XP to stop dumping RGSS104E.dll in my game folder as this way i can just rename the .dll


texts: Best Practice for Validating Components in Unity/C#?

texts:
In my game there's a Unit class, which all soldiers use.  Not all soldiers have special abilities which require unique class components (like Stealth class).  Special abilities either exist on a unit from the start, or never.

Special classes like Stealth are monobehaviour classes which provide specific functionality, and the fact a unit is or is not Stealth will need referenced by other classes.  For example, the classes which handle unit shooting and detection must check whether a unit in proximity is stealth. I'm wondering what is the best way to handle this case with Unity, given components?

Right now the Unit class' Start function checks if the special class exists, and assigns a private boolean to true.  This boolean can only get accessed by a get function.  Does this make sense for more easily readable and secure code?  Or is it overengineering?

private bool isStealth;

if (GetComponent<Stealth>())
{
    isStealth = true;
}

public bool IsStealth()
{
    return isStealth;
}


texts: How can I set up a 2D circular boundary in Unity?

texts:
I wanted to create a virtual analogue stick on Unity.

I figured a very simple, 2 part method setting up a tether to the middle of a doughnut-container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve.
I initially tried to create a 2D circle collider around the doughnut-container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut-container). Thus was done with multiple if statements:
 if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}
 if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}
 if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}
 if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;}

However, when testing the code out, the cursor still exceeded the boundaries given:

Minimum reproducible code for the cursor:
public class menuScript : MonoBehaviour
{
    public float speed;
    public Vector2 originPoint;
    private Vector2 currentPoint;
    // Start is called before the first frame update
    void Start()
    {
        Vector2 originPoint = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        currentPoint = transform.position;
        float step = 50 * Time.deltaTime;
        float vertical = Input.GetAxis("Vertical") * Time.deltaTime * speed;
        float horizontal = Input.GetAxis("Horizontal") * Time.deltaTime * speed;

        if (horizontal != 0 || vertical != 0)
        {
            transform.Translate(horizontal, vertical, 0);
            if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}
            if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}
            if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}
            if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;}
        }
        else
        {
            transform.position = Vector2.MoveTowards(transform.position, originPoint, step);
        }
    }
}


texts:
I am developing a game with XNA, and I am having trouble with resolutions. For now, I have only implemented the main menu, but I want to make a game that is independent of the resolution. As I am a beginner, I haven't taken into account the resolution, so far. When I changed the resolution, it gave me a real headache. The background image that I use has a 1920x1080 resolution, so it has an aspect ratio of 16:9. The initial resolution was 800x600, so the background image looks stretched. The same happens with resolutions with aspect ratio 4:3 (e.g. 640x480, 1024x768, etc.).

Before posting this question, I searched for information on the Internet. I found "XNA 2D Independent Resolution Rendering", and other similar solutions. The solution offered seems perfect for me, at first, because I wasn't thinking of using two resolutions; one internal, for drawing, and one that corresponds to the size of the window. However, I have been observing some problems.

When I enable fullscreen mode, and its resolution is lower than the desktop resolution, the game doesn't stretch the resolution to fill the entire screen. This makes the game draw at the center of the screen, but with a black border on both sides of the screen.

The aspect ratio of my background image is 16:9, however, the resolutions that I am trying have an aspect ratio of 4:3. With the page solution, I have the same problem; the background image seems to be stretched. I researched the code, to find a solution, and changed the RecreateScaleMatrix() function  to this:

private static void RecreateScaleMatrix()
{
    _dirtyMatrix = false;
    float aspect = 16.0f / 9.0f;
    _scaleMatrix =
        Matrix.CreateScale((float)_device.GraphicsDevice.Viewport.Width / _virtualWidth,
        (float)_device.GraphicsDevice.Viewport.Height / _virtualHeight, 1f) *
        Matrix.CreateScale(1, EngineManager.GameGraphicsDevice.Viewport.AspectRatio /
        aspect, 1) * Matrix.CreateTranslation(0, (_device.GraphicsDevice.Viewport.Height -
        (_device.GraphicsDevice.Viewport.Height / aspect)) / 4.0f, 0);
}

This seems to have solved the problem, but only on certain resolutions ,and further reducing the rectangle which show the final result.

I have been thinking about these problems all day, and I realized that without knowing the exact resolution of the image to draw, in advance (independent of aspect ratio), is almost impossible to draw an image clearly.

How do I solve my resolution problems?


texts: How to deal with data transfer between scenes

texts:
What i would like to achieve is to have 1 global 2d map where armies could move (Scene 1). When they collide, trigger loads new scene, setup parameters like army size etc (Scene 2). Once battle is finished, I would like to close scene2 and load again scene1.
I implemented this and had bad feelings about setting up Scene 1 into the same position as i left it(I used singletos for this).
Wouldnt it be better approach to hide Scene1, so all data will be consistent and once scene 2 is finished, show it again? Is it possible and is it good idea?

Another way I was thinking about was to create scene3 which would contain all important data needed for scene1 setup. So when I move from scene1 to scene2, i can destroy scene1. Once I finish scene2, I would start scene 1, which has its data inside scene 3 so scene setup would be done out of the box without defining some special scene init scripts.

Honestly I could not fight any proper solution for scene management, only tons of basic tutorials


texts: Need some advice regarding collision detection with the sprite changing its width and height

texts:
So I'm messing around with collision detection in my tile-based game and everything works fine and dandy using this method. However, now I am trying to implement sprite sheets so my character can have a walking and jumping animation.

For one, I'd like to to be able to have each frame of variable size, I think. I want collision detection to be accurate and during a jumping animation the sprite's height will be shorter (because of the calves meeting the hamstrings). Again, this also works fine at the moment. I can get the character to animate properly each frame and cycle through animations.

The problems arise when the width and height of the character change. Often times its position will be corrected by the collision detection system and the character will be rubber-banded to random parts of the map or even go outside the map bounds. For some reason with the linked collision detection algorithm, when the width or height of the sprite is changed on the fly, the entire algorithm breaks down.

The solution I found so far is to have a single width and height of the sprite that remains constant, and only adjust the source rectangle for drawing. However, I'm not sure exactly what to set as the sprite's constant bounding box because it varies so much with the different animations.

So now I'm not sure what to do. I'm toying with the idea of pixel-perfect collision detection but I'm not sure if it would really be worth it. Does anyone know how Braid does their collision detection? My game is also a 2D sidescroller and I was quite impressed with how it was handled in that game.

Thanks for reading.


texts: Easy way to set face colors with indexed VBOs?

texts:
I'm loading OBJs, which lend themselves well to setting up as indexed VBOs, since each vertex is only defined once and then a face definition will reference the same vertex more than once when they share an edge. I want to define face colors based on the materials loaded from the OBJ. This is quite easy in immediate mode, but I've realized that using VBOs will require me to duplicate each vertex in order to have two adjacent faces with different colors. What's the best way to go about solving this without duplicating vertices?

EDIT: Code (LWJGL)

//Get the VBO from the GPU
glBindBuffer(GL_ARRAY_BUFFER, vbo);
//Tell OpenGL what to expect from the VBO
glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); //Location
glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex.SIZE * 4, 4 * 3); //Texture Coord
glVertexAttribPointer(2, 3, GL_FLOAT, false, Vertex.SIZE * 4, 4 * 3 + 4 * 2); //Normal

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0);


texts:
In my game (simple RPG with Java) there will be an abstract class Creature.

Critter, Beast, Vampire... will inherit from Creature. But not ALL classes that inherit from Creature will have an inventory.

Should I

a) make another abstract class such as CreatureWithInventory and inherit from it?

or

b) make an interface such as Inventory and make stuff as (Vampire implements Inventory)?

Is there a reason to prefer one over the other? Any considerable trade-offs?

Should Inventory itself be a class and let some Creatures have a field for it? If so, how would I test if Creature foo has Inventory? Is that even possible?


texts: Did they remove Sprite sorting layers from Unity?

texts: I can't figure out how to set it. I thought it was a setting on the sprite renderer but it doesn't seem to be there? Google isn't turning up any results.


texts: How can I spawn multiple monsters in my game?

texts:
I made a little iPhone game in which I want to make multiple monsters spawn.

I have one UIImageView called enemy that spawns at beginning of the game. But I want it to spawn many more monsters until I say it needs to stop spawning them.

I know how to get random locations. This question is a follow up to this one.


texts: UDP non-blocking or a separate thread for receiving?

texts:
I am creating a multiplayer game (for under 64 players). I already decided to have a separate thread for the network loop, but I was wondering if it would be better to create an extra thread for receiving UDP or set the receiving socket on non-blocking (without extra thread).

Or is it better to use another method like Asynchronous Sockets? Better methods are always welcome!


texts:
I want to access specific colliders(to see if they are been clicked) from one script insted of making multiple scripts for every collider.How?

I am using unity.

using UnityEngine;
using System.Collections;

public class MainMenuManager3D : MonoBehaviour
{
    public enum Menu
    {
        MainMenu,
        NewGameMenu,
        LoadGameMenu,
        OptionsMenu,
        GameSettingsMenu,
        GameGraphicsMenu,
        Exit
    }
    public Menu currentMenu;
}

I want to change the currentMenu based on which collider is clicked in this script. Insted of making 99999 scripts for every collider.