texts: What is the name for the little numbers that appear over characters' heads when they lose health?

texts: ...you know the ones. Something like "value overlays" or "value pop-ups" describes them quite well, but I was thinking they might have a real name?


texts: 2D physics performance on iPhone/Android using Unity 3D?

texts:
I've been looking into making 2D games with Unity. One thing which concerns me is the performance of the physics engine. Since Unity is a 3D game engine I'm going to have to assume it uses a 3D physics engine. Obviously I can turn this 3D engine into a 2D one by locking off various axis such that objects only move physically in 2D space.

However this worries me, for example Box2D being a specialized 2D physics engine is optimized for 2D. Would the physics in Unity3D be fast enough to say, duplicate the sorts of physics we see in games like Angry Birds on a handheld device?


texts: Constantly Checking Collisions and OnTriggerEnter

texts:
Ok so i wanted to ask a basic question.
suppose i have an edge collider 2d,

Fact - if i add the OnTriggerEnter() into my code. it will check for trigger enters constantly.

Now,
If the edge collider exists but i don't put OnTriggerEnter(), will the game still check for trigger enter collisions? or will it not check for them?


texts: Can a prefab of a complete Unity scene be created?

texts: Can we create a prefab out of a complete unity scene, so that we can instantiate the complete scene like we instantiate gameobjects in unity.


texts: How to store an array into a texture and sampler the texture in vertex shader correctly?

texts:
I'm a new learner about OpenGL and GLSL. I'm coding a program in which i wanna store a group of datas in a texture and get the data by sampling the texture in vertex shader. Then i want to set the datas as the y coodinates of terrain positions. But i get a trouble that it's failed and i can't get a correct value___all the y coodinates are 0.

The main code is below:

GLuint  terrainShader;      // The perspective demonstration shader
GLint   locMVP,locTex;                 // The location of the uniform in vertex shader

GLuint  vao;                    // The VAO
GLuint  vertexBuffer;
GLuint elementBuffer;
GLuint vertexTexture;

const int n=127;
float verteces[n*n*2];// vertex array
GLuint vIndexFine[(n-1)*2*n];//index array
GLsizei countFine[n-1];
GLvoid* offsetFine[n-1];

float *data=new float[n*n];
    terrainShader = gltLoadShaderPairWithAttributes("terrain.vp", "terrain.fp", 1,
                                    GLT_ATTRIBUTE_VERTEX, "vVertex");

    locMVP = glGetUniformLocation(terrainShader, "mvpMatrix");
    locTex = glGetUniformLocation(terrainShader, "vertexTexture");

    //creat a terrain with size of n*n
    for(int i=0;i<n;i++)
    {
        int sum=i*n;
        for(int j=0;j<n;j++)
        {
            verteces[(sum+j)*2]=float(j);
            verteces[(sum+j)*2+1]=float(i);
        }
    }
    //initialize the index array
    for(int i=0;i<n-1;i++)
    {
        if(i==0)                //the first line
        {
            for(int j=0;j<n;j++)
            {
                vIndexFine[2*j]=j;
                vIndexFine[2*j+1]=j+n;
            }
        }
        else
        {                   //if it's not the first line,then just add n to get the indexes of new line
            for(int k=0;k<2*n;k++)
            {
                vIndexFine[i*2*n+k]=vIndexFine[(i-1)*2*n+k]+n;
            }
        }
    }

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verteces), verteces, GL_STATIC_DRAW);
    glVertexAttribPointer(GLT_ATTRIBUTE_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray(GLT_ATTRIBUTE_VERTEX);

    glGenBuffers(1, &elementBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vIndexFine), vIndexFine, GL_STATIC_DRAW);
        //initialize data array with random integers between 1 and 100
    for(int i=0;i<n*n;i++)
        data[i]=float(rand()%100)/100.0;

        //creat a texture and store data
    glGenTextures(1, &vertexTexture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, vertexTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, n,n, 0,GL_RED, GL_FLOAT, data);

    //compute every trianglestrip's indexcount and offset
    int temp=n*2*sizeof(GLuint);
    for(int i=0;i<n-1;i++)
    {
        offsetFine[i]=(void*)(temp*i);
        countFine[i]=GLsizei(n*2);
    }

    glUseProgram(terrainShader);
    glUniform1i(locTex, 0);

    modelViewMatrix.PushMatrix(viewFrame);
    modelViewMatrix.Translate(-n/2.0, -10.0f, -n/2.0);
    glUniformMatrix4fv(locMVP, 1, GL_FALSE, transformPipeline.GetModelViewProjectionMatrix());
    glMultiDrawElements(GL_TRIANGLE_STRIP,countFine,GL_UNSIGNED_INT, (const GLvoid**)offsetFine,n-1);
    modelViewMatrix.PopMatrix();

the vertex shader:

#version 410

uniform mat4    mvpMatrix;
uniform sampler2D vertexTexture;
in vec2 vVertex;

void main(void)
    {
    vec2 vTexCoords=vVertex/127.0;
    float height = texture2DLod(vertexTexture, vTexCoords,0.0).x*100.0;
    vec4 position=vec4(vVertex.x,height,vVertex.y,1.0);
    gl_Position = mvpMatrix * position;
    }

i think  the mistake must be the part of storing datas in application or the part of fetching datas from  the texture in vertex shader. can sombody point it out for me?


texts: Reason for white lines in tile-based game

texts: My game is tile-based. I am getting this lines between two tiles. They don't look nice. How can i resolve this issue?


texts: Online multiplayer. Provoke lagged move on local player

texts:
I am developing an online multiplayer 2D videogame with Unity as a client and a server programmed in c ++.
I do the synchronization of movement through an interpolation so that the movement is smoothed, but I have a doubt that I cannot find an answer anywhere.
In any multiplayer game when the client has a bad connection (lag) the character moves awkwardly and not fluidly, but in reality I don't understand why this behavior happens, currently in my game even though the client has a bad connection, it moves from fluid form because movement management is done locally and what is sent to the server is the player's position.
How can I produce this in my game?
Thank you very much and sorry for my level of English. Thank you


texts:
Why does an emulator use more RAM than the original system? What are emulators doing that requires so much more power?

For example, when using the PSP emulator PPSSPP I'm experiencing lag on a modern PC with gigabytes of RAM, even though the PSP runs with only 32MB of RAM.

When developing my own console emulator, should I not expect it to use a similar amount of RAM / CPU cycles / other resources as the original system has to offer? Or is there extra overhead that makes emulating much more demanding than what the original hardware's specs would suggest?


texts: How do I calculate the forces exerted by a taut wire wrapping 2D objects?

texts:
Assume I have a physics primitive I am going to call a "wire", wrapped around a 2D environment (as described in this question).

Here's an illustration of what that might look like:

In the example illustration: The box is being pulled upwards (held up) by the wire, and the box is pulling the wire downwards. The object on the spring is being pushed downward by the wire, but is also pushing the wire upwards.

While I haven't figured out how to implement it yet, assume the wire will slide freely across the points that it is wrapped around.

In a 2D physics simulation (ie: frame based) how do you calculate the forces (or impulses) to apply to the objects that are attached to or wrapped by a wire like this?

As I alluded to in my first question, I imagine that if the only non-static object "on" the wire was the mass at the end, then the force would be identical to a fixed-length joint between the mass and the point before that on the wire.


texts: Issue with tangents/bitangents generation for normal maps

texts:
I'm generating tangents and bitangents for a normal mapping effect and while using the same method as several tutorials, I get tangents that are not very continuous.

Here, we can see on the sphere especially that the tangents are very weird.

Also, my normal are totally correct and don't have this issue.

And when using these tangents with my normal mapping shader they "work", but create a very harsh "break" in the surface.

Here is the code used to generate the tangents and bitangents :

for (size_t i = 0; i < out_vertices.size(); i += 3)
{
  const auto& v0 = out_vertices[i];
  const auto& v1 = out_vertices[i + 1];
  const auto& v2 = out_vertices[i + 2];

  const auto& uv0 = out_uvs[i];
  const auto& uv1 = out_uvs[i + 1];
  const auto& uv2 = out_uvs[i + 2];

  const auto& dd_v0 = v1 - v0;
  const auto& dd_v1 = v2 - v0;

  const auto& dd_uv0 = uv1 - uv0;
  const auto& dd_uv1 = uv2 - uv0;

  float r = 1.0f / (dd_uv0.x * dd_uv1.y - dd_uv0.y * dd_uv1.x);
  glm::vec3 tangent = glm::normalize((dd_v0 * dd_uv1.y - dd_v1 * dd_uv0.y) * r);
  glm::vec3 bitangent = glm::normalize((dd_v1 * dd_uv0.x - dd_v0 * dd_uv1.x) * r);

  out_tangents.push_back(tangent);
  out_tangents.push_back(tangent);
  out_tangents.push_back(tangent);

  out_bitangents.push_back(bitangent);
  out_bitangents.push_back(bitangent);
  out_bitangents.push_back(bitangent);
}

I'm not sure if I need to average the (bi)tangents that share the same vertices/uvs, but I'm also not sure how to do it.

Thanks for any help.


texts: Why is my player movement code not working?

texts:
I'm trying to make my 2D character able to float around the screen, but my code isn't working:

using UnityEngine;

public class playermovement : MonoBehaviour
{

    public float moveSpeed = 5f;

    public Rigidbody2D rb;

    Vector2 Movement;

    public Vector2 Movementspeed { get; private set; }

    // Update is called once per frame
    void Update()
    {
        Movement.x = Input.GetAxisRaw("Horizontal");
        Movement.y = Input.GetAxisRaw("Vertical");
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + (Movement * Movementspeed * Time.fixedDeltaTime));
    }
}


texts:
I've made a simple 2D game engine using C# and DirectX and it's fully functional for the demo I made to test it. I have a Timer object that uses QueryPerformanceCounter and I don't know what's the better choice: use only one timer in the game loop to update everything in the game, or an independent timer in every object that needs one.

My worry is that when I try to implement threads, what will happen with timers? What happens with the sync?


texts: How can I use a camera matrix with different resolutions?

texts:
I created a little jump'n'run game. The character(Mario) is always the center of the viewport. The game is running correctly if I use the resolution 800x480 pixel. But when I use another resolution(for example 1280x768), the sprites in the viewport look completely different to the sprites in the 800x480 viewport. I want that the viewport(and the sprites in the viewport) looks always the same, on every single resolution.

How can I do that? Should I change something on my camera matrix parameters or what should I change so that the viewport and the proportions of the sprites look always the same?

I use Monogame to run the game on different Windows Phone devices.

My camera class:

 public class Camera
{
    public Vector2 Cameraposition;

    public Camera(Vector2 cameraposition)
    {
        Cameraposition = cameraposition;
    }

    public void Update(GameTime gameTime, Vector2 CamPosition)
    {
        Cameraposition = CamPosition;
    }

    public Matrix GetMatrix()
    {
        return new Matrix(1, 0, 0, 0, 0, 1, 0, 0, Cameraposition.X, Cameraposition.Y, 1, 0, -Cameraposition.X, -Cameraposition.Y, 0, 1);
    }
}

In Game1:

//I use the camera in Game1 like this:
//At the beginning(in LoadContent):
Vector2 cameraposition = new Vector2(PlayerStartpos.X - GraphicsDevice.Viewport.Width / 2, PlayerStartpos.Y - GraphicsDevice.Viewport.Height / 2);
camera = new Camera(cameraposition);

//Updating the camera position
 protected override void Update(GameTime gameTime)
    {
        player.Update(gameTime);
        Newcameraposition = new Vector2(player.Playerposition.X - GraphicsDevice.Viewport.Width / 2, player.Playerposition.Y - GraphicsDevice.Viewport.Height / 2);
        camera.Update(gameTime, Newcameraposition);

        base.Update(gameTime);
    }

//Drawing:
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, camera.GetMatrix());
 ...


texts: I need a map generation algorithm for towerdefense

texts:
I'm making a simple JavaScript tower defense game, I've experimented on some map generation my self, i seem to get one that works properly.

What I want is for you to provide a start point (possibly an end point) and an algorithm to generate a random path between them in a tower defense like style.

Examples


texts: Is it a good idea to use a single sqlite database to store all occurring multiplayer matches?

texts:
I have a turn based strategy game for desktop and mobile, the game app uses a sqlite database to play local games. There's nothing special about the database design, I have tables to keep track of units in the game, player commands, etc.

I want to implement multiplayer now on a dedicated game server, and am thinking of using the same setup as the client apps. I'd create a sqlite db on the server file system for each game my users create. I'm expecting around 1,500 simultaneous games (based on other games I've run).

Here are the pros I imagined:

I can reuse all the game code as-is - I just point the game wrapper server-side to a sqlite db on the server machine.
Cheap to start and delete games (happens quite often with turn based games).

Downsides:

Hitting disk a lot, since sqlite is a wrapper around a file basically (my game server has SSD drives, tho).
Portability - I'd have a mess of sqlite files on the file system. If I have to move servers, could be a little gross copying them to a new machine. Also have to check the # of files in a directory limit for my OS, or shard them.
Front end synchronization - I'd still have to have a centralized mysql db or similar to keep track of all the individual games on disk, their general states (started, waiting, ended etc) for general user queries on their games list.

I'd be interested if anyone has tried a setup like this. I can always use a single mysql instance and one set of tables shared between all games, just need to add a gameId column to separate all the data. It would be interesting to see the Units table though with millions of rows shared between all the games.

Thanks


texts:
I'm making a game using java. I'm wondering what would be the best way to store games options (like screen height and width, full screen boolean and many other similar options the user can select) at run time?

Currently, I read the options from a text file so everything that comes out of the reader is a string. I would like to add the value of the string to the appropriate variable in as few steps as possible. I would also avoid having to code getters and setters for all variables there is and have a general getter and setter that takes the name of the option as a parameter.
ex:

    public void set(String name, Object value){
        options[name] = value;
    }

    public Object get(String name){
        return (Object options[name]);
    }

I was thinking about a hashmap of variable names and values but the problem is: not all variables are of the same type, I'll have ints and doubles and booleans. so what would be the best way to store all those different variable types and access them with general calls? Should I leave them as Object and cast them as I need to use them? Or do i really have to set them all manually in my code (which would be quite the hassle should i decide to add more options down the line)?

UPDATE: So, here's the code i got so far for serialization but still not working:

Options.java:

public class Options implements java.io.Serializable{

//Final variables declaration
static transient final String SAVE_DIR = System.getProperty("user.dir") + "\\res\\saves\\";
static transient final String OPTION_FILE = "options.ser";

//Static variables declaration
public int s_width;
public int s_height;
public float fov;
private static transient Options instance;

private Options()
{
    this.s_width = (this.s_width == 0)? 800 : this.s_width;
    this.s_height = (this.s_height == 0)? 600 : this.s_height;
    this.fov = (this.fov == 0)? 60 : this.fov;
}

public static Options GetInstance()
{
    if(instance ==  null)
        instance = new Options();
    return instance;
}

Serializer.java:

public class Serializer {
private static Options o = Options.GetInstance();

    public static void loadOptions()
    {
        File dir = new File(Options.SAVE_DIR);
        if(dir.exists())
        {
            File file = new File(dir + "\\" + Options.OPTION_FILE);
            if(!file.exists())
            {
                saveOptions();
            }

            try {
                FileInputStream fileIn = new FileInputStream(file);
                ObjectInputStream in = new ObjectInputStream(fileIn);
                o = (Options) in.readObject();
                in.close();
                fileIn.close();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        else
        {
            dir.mkdir();
            saveOptions();
        }
    }

    public static void saveOptions()
    {
        File dir = new File(Options.SAVE_DIR + "\\" + Options.OPTION_FILE);
        try {
            if(!dir.exists())
            {
                dir.createNewFile();
                o = Options.GetInstance();
                System.out.println("otpion.ser created and initialised succesfully!");
            }
            FileOutputStream f = new FileOutputStream(dir);
            ObjectOutputStream out = new ObjectOutputStream(f);
            out.writeObject(o);
            out.close();
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


texts:
I have an array of objects tied to a global array in GMS2
When I try to reference the variable used to position the object I get errors saying the variable hasn't been declared.
The error also says the object and variable that cause the error are unknown.
I feel like I'm using the nested reference to point to the current target of the for loop incorrectly.

//Place is a local variable used as a index for the array
 Global.hand[place] = noone;
 //The array global.hand is elsewhere set as a 1d array that's 8 items tall
 For(i = place + 1; i < 8; i++)
 {
     Global.hand[i] = global.hand[i + 1];
     Global.hand[i].place -= 1;
 }
 Place = instance_count(card);

The snippet is supposed to take an item in the array and move it to the end

The line that's causing the error is Global.hand[i].place -= 1;


texts: How to change Texture2D type to Sprite during runtime (Unity)

texts:
How can we convert the Texture2D type to "Sprite" using the script (not in Editor)?
It seems that the Texture2D retrieved from file is by default Normal Map.
I need to convert the TextureType to "Sprite".

Texture2D texture = LoadPNG("D:/download.jpg");
testPlaneRenderer.material.SetTexture("_source",texture);

LoadPNG method code:

 public static Texture2D LoadPNG(string filePath)
{

    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);
        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
        Debug.Log("File Exists!");
    }
    else
    {
        Debug.LogError("File not exists!");
    }
    return tex;
}

It seems that this texture is set as "Default" or "Normal" Type when imported from file and then assigned to Material dynamically. As the particular shader I'm using, works best if the Texture Type is set to Sprite (I tested it by manually placing the texture file in Project and then assigning the texture to Material).

I need to change Type of Texture to Sprite before assigning it to the material.
I've seen options like "AssetImporter" but it only works in Editor.

The effect of the shader (which takes two texture types

a) Inverted & Blurred Texture

b) GrayScale Texture

And then returns a Sketch Effect to the object. I convert the original image to inverted & blurred, grayscale texture using some image processing code (C#, Unity -> working around with GetPixels and SetPixels)...

Output with Defualt Texture Type

Output with Sprite Texture Type


texts: How do I calculate the angle of the slope at a point on a 2D bitmap terrain?

texts: I have an arbitrary destructible bitmap terrain like the one in "Worms". It's easy to work out if a character or missile intersects the terrain, but how do I work out the angle of the slope at the contact point, so I can make grenades roll down hills, bounce off at the right angle, etc. I know it can be down by somehow taking a sample of points around the impact point and seeing which ones intersect, but I'm not sure exactly how to go about it, and in an efficient way.


texts:
I am doing some physics for a platformer game in MonoGame. The jump height changes based on FPS even though I'm using delta time. When the FPS decreases and gravity is added before movement, the jump height is shorter than usual. How do I keep a consistent jump height at all frame rates?

Here's the pseudo-code executed each frame:

velocity.Y += gravity * dt;
Move(velocity * dt);


texts:
I am making a small game like Kerbal Space Program. What I do is when I am over a certain height, I render the planet or moon as a sphere. Each planet or moon will have a generation seed to generate the terrain when I am going to land. This works really well with an earth like planet.

To generate a surface map for an earthlike planet, I just use 3d rotation to see where the point on the map is in a 3d coordinate space, and take its perlin noise value as height (I also use other factors to see what the terrain looks like, but I just start with a height).

This gives me a beautiful mountain, hill kind of landscape, which works good for watery planets. However, moons and rocky planet terrains have a lot of craters &  I have no idea how I am going to do with noise.

Also I am using noise so I wouldn't have to save an entire terrain by itself for a celestial body's surface, I use it so I can see where I am on the planet, and generate the height from there. If there are other solutions please tell.


texts: What are the advantages of constraint-based solvers?

texts:
I am a fairly competent programmer and I am not bad at math. I have been working on game physics simulations for around 2 years now.

In some books and tutorials that I have read, they introduce constraints. They calculate Jacobian matrices and use Baumgarte constants and all that complicated stuff.

Even when I try really hard and follow their logic, I always feel lost. It is not that the mathematics or algorithms of the technique are too complicated. It is just that when things like Jacobian matrices enter the picture, it is not intuitive anymore.

In my experience applying simple impulses to resolve collisions have given satisfactory results.

So my concern is: What am I losing by not utilizing constraints? What are the situations that can benefit from having constraints? Maybe some complicated objects with joints under inverse kinematics for example?

For example:
http://twvideo01.ubm-us.net/o1/vault/gdc09/slides/04-GDC09_Catto_Erin_Solver.pdf
and
http://www.bulletphysics.com/ftp/pub/test/physics/papers/IterativeDynamics.pdf


texts: How do I convert a PNG into a pixel art font for use in Godot?

texts:
I'm an artist. I have several pixel art fonts prepared like so. My platform, Godot, accepts only TrueType and FNT file formats. My images are of raster pixels so obviously a conversion needs to take place. Vector graphics are fine, but I'd like to keep the pixel squares in my design and have them remain aligned with the pixels on screen.
Is anyone aware of a method to build a font from a PNG without too many headaches? I could always make my own text writer using sprites, but that sounds like meaningless reduplication of effort when I Godot provides such useful Label nodes.


texts: Why does rotating a polygon also translates it in libGDX?

texts:
I'm using polygons for collision detection. Here is the code:
poly = new Polygon(verticies);
poly.setOrigin(100,100);
poly.setRotation(45);
renderer.setColor(Color.GREEN);
renderer.begin(ShapeType.Line);
renderer.identity();
renderer.translate(poly.getOriginX(), poly.getOriginY(), 0);
renderer.polygon(poly.getTransformedVertices());
renderer.translate(-poly.getOriginX(), -poly.getOriginY(), 0);
renderer.end();

Result, polygon is rotated, but it moves to the right. Here is the picture for 0, 30, 45, 60 , 90 degrees (from left to right). What am I doing wrong?


texts: Outline Shader Effect for Orthogonal Geometry in XNA

texts:
I just recently started learning the art of shading, but I can't give an outline width to 2D, concave geometry when restrained to a single vertex/pixel shader technique (thanks to XNA).

the shape I need to give an outline to has smooth, per-vertex coloring, as well as opacity. The outline, which has smooth, per-vertex coloring, variable width, and opacity cannot interfere with the original shape's colors.

A pixel depth border detection algorithm won't work because pixel depth isn't a 3.0 semantic.
expanding geometry / redrawing won't work because it interferes with the original shape's colors.

I'm wondering if I can do something with the stencil/depth buffer outside of the shader functions since I have access to that through the graphics device. But I don't believe I'm able to manipulate actual values.

How might I do this?


texts: Set texture of a LHSprite that is loaded from LevelHelper

texts:
How do i set the image/texture of an LHSprite that is loaded into xCode using levelHelper & spriteHelper?

I am using sprite sheets. So i tried to load the image the old fashioned way using CCSpriteFrameCache, but unfortunately it isnt recognizing the .pshs file :( Any Help would be great!


texts: Having Trouble holding PlayerPrefs after game restart

texts:
I am trying to create a highscore value that is stored in playerprefs, and only updates when a higher score is achieved. I got playerprefs viewer on the asset store, and can see that it is holding a value, but it seems that it blows through the if statement that checks to see if the new value is a highscore. This means that no matter what score I get, it always stores it as a highscore.

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

public class Score : MonoBehaviour
{
    public Transform Player;

    public Text scoreText, Highscoretext;

    public GameObject Postgame, Ingame;

    private bool stopScore = false;

    void Update()
    {
        if (stopScore == false)
        {
            //Keeps track of and displays current score
            float floatscore = Player.position.x;
            int intscore = (int)floatscore / 10;
            if (FollowPlayer.gameOver == false)
            {
                scoreText.text = intscore.ToString();
            }

            if (FollowPlayer.gameOver == true)   // Checks wheather the game has ended (from a different script)
            {
                stopScore = true;   // Stops running the score function

                if (intscore > (PlayerPrefs.GetInt("HighScore")));   // Checks to see if the score of the current game is a new Highscore
                {
                    PlayerPrefs.SetInt("HighScore", intscore);   // Sets new Highscore

                    EndScreen();   // Function to load the endscreen
                }
            }
        }
    }
    public void EndScreen()
    {

        Highscoretext.text = "Highscore: " + PlayerPrefs.GetInt("HighScore").ToString();   // Supposed to set the endscreen Highscore value to the new Highscore value

        // Different canvas overlays
        Postgame.gameObject.SetActive(true);
        Ingame.gameObject.SetActive(false);
    }
}

I tried using Debug.Log to debug this, and found that even if intscore is smaller than PlayerPrefs.GetInt("HighScore")), it will still run the code that sets a new highscore.
Anyone have any idea of how to fix this?


texts: How do I calculate to and from a Non-Linear Acceleration?

texts:
I am looking at non-linear accelerations using the following values:

initial_acceleration
time_to_max_velocity
max_velocity
current_velocity

Initial_acceleration is the per frame acceleration we start with from 0 velocity. Over the course of "time_to_max," the acceleration is supposed to follow an interpolation from this value to whatever it needs to be to be to hit max_velocity at the end of this time. I need code both to generate the velocity generated by this function at a given point in time, and code for an inverse function that gives me the time given a current velocity.

It sounds like what I want is a type of quadratic interpolation or spline, but I have been unable to work out the details. Above I've graphed some values:

Red shows the case where: initial_acceleration * time_to_max == max_velocity
Green shows the case where: initial_acceleration * time_to_max > max_velocity
Blue shows the case where: initial_acceleration * time_to_max < max_velocity

The speed curves I've tried in code chaining lerp operations together always end up doing weird things like curving over my max speed and then back down to max speed again. If anyone can supply code, or math, that could get me even halfway towards an answer, I would be very appreciative.


texts: What happened with server code on deployment to Heroku

texts:
I'm starting to learn about making games on the web and am using this agario clone on GitHub to help.

I've succeeded in setting up a version on Heroku using the instructions from here. I've never used Heroku before, so I'm a little lost on a few more things. The link from the instructions allowed the files to be directly transferred from GitHub. However, I can't seem to view them at all from Heroku - I can only run the client with 'Open app' (which works).

What exactly happened when I deployed the app? Did Heroku immediately start running the server code and will it continue to indefinitely do so even if no clients are connected?


texts: What is the best way to "carve" a terrain created from a heightmap?

texts:
I have a 3d landscape created from a heightmap. I'd like to "carve" some holes in that terrain. That will allow me to create bridges, caverns and tunnels inside it.

That operation will be done in the game editor so it doesn't need to be realtime. In the end, rendering is done using traditional polygons.

What would be the best/easiest way to do that ? I already think about several solutions :

Solution 1

1) Create voxels from the heightmap (very easy). In other words, fill a 3D array like this : voxels[32][32][32] from the heightmap values.

2) Carve holes in the voxels as i want (easy too).

3) Convert voxels to polygons using some iso-surface extraction technique (like marching cubes).

4) Reduce (decimate) polygons created in 3).

This technique seems to be the most promising for giving good results (untested). However the problem with marching cubes is that they tends to produce lots of polygons thus reducing them is mandatory. Implementing 4) also seems not trivial, i have read several papers on the web and it seems pretty complex. I was also unable to find an example, code snippet or something to start writing an algorithm for triangle mesh decimation.
Maybe there is a special decimation algorithm (simpler) for meshes created from marching cubes ?

Solution 2

1) Create some triangle mesh from the heighmap (easy).

2) Apply severals 3D boolean operation (eg: subtraction with a sphere) to carve the mesh.

3) apply some procedure to reduce polygons (optional).

Operation 2) seems to be very complex and to be honest i have no idea how to do that. Also applying many boolean operation seems to be slow and will maybe degrade the triangle mesh  every time a boolean operation is applied.


texts: Why are meshes limited to 65k indices or uint16 in most game engines?

texts:
Why are most game engines like unity limiting their meshes to 65k indices by default, or enforcing to use uint16 as the default datatype for indexbuffers?

I know that its better for performance to use uint16 indexbuffers, but I think there might be more reasons, because webGL 1.0 specification allows only uint16 vertexbuffers. I know that it's possible to use uint32 indexbuffers in webGL if the "OES_element_index_uint" extension is available in webGL 1.0 devices.

How big is the performance impact when using uint32 indexbuffers instead of uint16 indexbuffers? I think the only difference is in the memory bandwidth during the initial upload of the indices and should not matter much during runtime.


texts: Framerate drop from 160 to 56-59 when upgrading Unity to 2020

texts:
I just updated to Unity 2020.2 from Unity 2019.4. I use Ubuntu 2020.10. Everything is super fast but the framerate is less than 60 FPS, precisely between  56 and 59 FPS, for all my Android project. With Unity 2019.4, it was more than 160 FPS. Even Unity Sample scene has this framerate.
Is this bug on my laptop or a configuration set by Unity? How can I edit it to get my previous framerate?


texts: What is the easiest way to move towards and along the edge on a hex grid?

texts:
I have a hexagonal grid with variable radius. My entity can move exactly two hexes per turn.

How should I calculate next step towards border and afterwards travelling clockwise around map?

Preferred movement at the boundary

Character should stay at the border while moving counter-clockwise every turn.

Example movement at the middle

Character should move 1 or 2 hexes towards edge every turn.

I can't figure out simple math to do this.

Edit:

This is how I did movement at the boundary:

  var x = pos.x;
  var y = pos.y;
  var z = -pos.x-pos.y;
  var dx =  0;
  var dy =  0;

  if      (x == -radius && z >   1) {          dy =  2; }
  else if (x == -radius && z ==  1) { dx =  1; dy =  1; }
  else if (y ==  radius && x <  -1) { dx =  2           }
  else if (y ==  radius && x == -1) { dx =  2; dy = -1; }
  else if (z == -radius && y >   1) { dx =  2; dy = -2; }
  else if (z == -radius && y ==  1) { dx =  1; dy = -2; }
  else if (x ==  radius && z <  -1) {          dy = -2; }
  else if (x ==  radius && z == -1) { dx = -1; dy = -1; }
  else if (y == -radius && x >   1) { dx = -2;          }
  else if (y == -radius && x ==  1) { dx = -2; dy =  1; }
  else if (z ==  radius && y <  -1) { dx = -2; dy =  2; }
  else if (z ==  radius && y == -1) { dx = -1; dy =  2; }

Any ideas how should I clean this up?

Shortest path to boundary is probably easiest to calculate from x, y and z.


texts: How to avoid assigning the same GameObject individually for every prefab?

texts:
In many times, prefabs that share the same script may require the same GameObject in the script. For example, in my game I want to make a series of card prefabs. Each card has their own image when shown, but has the same back image when hidden. My script for card is:

public class DraggingCard : DragAndDropItem
{
    public Sprite secretSprite; //This is the same for every card
    Sprite oringinalSprite; //This is individual for every card
    Image image;

    public void Awake()
    {
        image = GetComponent<Image>();
        oringinalSprite = image.sprite;
    }

    public void Activate()
    {
        image.sprite = oringinalSprite;
    }

    public void Hide()
    {
        image.sprite = secretSprite;
    }
}

But if I write this, I'll have to assign the secretSprite in the inspector for every DraggingCard prefab. I tried to set secretPrefab to be static or const but neither worked.

I believe there must be a clever way to avoid the repeat work. Could anyone tell me that? Thank you!


texts:
Let's say one has a black/gray/white mask and wants to draw picture A over the white/gray values and picture B over the black/gray values (the blacker the more B picture). The best I come up with would be something like:

Set to RenderTargetA
Draw Mask
Draw PictureA over Mask (using DepthStencilState)
Set to RenderTargetB
Draw Mask
Draw PictureB over Mask
Draw both RenderTargets over each other somehow

But that just seems a) overly complicated and b) both render targets still have the mask drawn on them so it wouldn't have worked anyway. So how would one achieve this?


texts:
I am making a game for android and in it I am using sensors which are not available in the emulator. At the moment I am connecting my device and transferring the apk, then installing to test but that is a pain to do, and I have gotten to the stage where I need to start logging values for debugging. I have gone into the run configs of my app and set it to prompt me to pick a device, but my device is never in the list when it is connected to my PC and I try to run it. How am I supposed to set it up to work properly?

Thanks for the help.


texts:
I'm building a pixel art game with pygame, and I'd like to scale it to double the size. I have tried the pygame.transform methods like scale and scale2x, but they seem to alter the colors quite badly, there's an added red hue. Is there a way to scale pixel art correctly in pygame? Basically making each pixel 2x2 of the same color. Or do I have to do it manually, if yes, any suggestions?

This is the setup I have currently, "works" but messes up the colors:

#set scaling
scaling = 1

screen = pygame.Surface( (screen_w, screen_h) )
window = pygame.display.set_mode( (screen_w * scaling, screen_h * scaling) )

while not done:

    #do things...

    pygame.transform.scale(screen, (screen_w * scaling, screen_h * scaling), window)
    pygame.display.update()

E. for reference, here's what happens.

No pygame scaling

vs. pygame scaling


texts: Why is my cursor not working if I add a scaling matrix?

texts:
After moving the camera to any direction, my cursor isn't getting drawn on the correct position. For example: I move my camera to the right, after that I click on the screen, but the cursor isn't getting drawn on the place I clicked. It's drawn somewhere else on the screen.
Why is the cursor not getting drawn on the place I clicked?

I need to scale the screen because I want to support different resolutions in a MonoGame project(see my other question): How can I use a camera matrix with different resolutions?

I scale like this:

UPDATE:
I added the code that I'm using to get the cursor position, and the code that I'm using to draw the cursor. In addition, I use now Matrix.Invert(scaleMatrix * camera.GetMatrix())), but it doesn't work. The cursor is still drawn on the wrong position.

//In my Player class, I get the position of the click(Tap)
//The Playerposition is the center of the camera

public void Update(GameTime gameTime)
{
  while (TouchPanel.IsGestureAvailable)
  {
    GestureSample gs = TouchPanel.ReadGesture();
    switch (gs.GestureType)
    {
        case GestureType.HorizontalDrag:
          Playerposition += new Vector2(gs.Delta.X / game1.scaleX, gs.Delta.Y / game1.scaleY);
        break;
        case GestureType.VerticalDrag:
          Playerposition += new Vector2(gs.Delta.X / game1.scaleX, gs.Delta.Y / game1.scaleY);
        break;
        case GestureType.Tap:
          game1.CursorPosition = new Rectangle((int)(gs.Position.X / game1.scaleX), (int)(gs.Position.Y / game1.scaleY), 10, 10);
          game1.Clicked = true;
        break;
    }
  }
}

  //In Game1:
  public const int VirtualScreenWidth = 800;
  public const int VirtualScreenHeight = 480;
  public float scaleX, scaleY;
  private Vector3 _screenScale;

  protected override void LoadContent()
  {
    scaleX = (float)GraphicsDevice.Viewport.Width / (float)VirtualScreenWidth;
    scaleY = (float)GraphicsDevice.Viewport.Height / (float)VirtualScreenHeight;
    _screenScale = new Vector3(scaleX, scaleY, 1.0f);
  }

  protected override void Update(GameTime gameTime)
  {
   player.Update(gameTime);
   //Updating the camera position:
   Newcameraposition = new Vector2(player.Playerposition.X - (float)VirtualScreenWidth / 2, player.Playerposition.Y - (float)VirtualScreenHeight / 2);

   camera.Update(gameTime, Newcameraposition);

   InvertCursorPos = Vector2.Transform(new Vector2(CursorPosition.X, CursorPosition.Y), Matrix.Invert(scaleMatrix * camera.GetMatrix()));

   //Calculate the cursor position
   if (Clicked == true)
   {
     CursorPosition = new Rectangle((int)(InvertCursorPos.X + Newcameraposition.X), (int)(InvertCursorPos.Y + Newcameraposition.Y), 10, 10);
     Clicked = false;
   }

   base.Update(gameTime);
  }

  // Drawing
  protected override void Draw(GameTime gameTime)
  {
  GraphicsDevice.Clear(Color.CornflowerBlue);
  var scaleMatrix = Matrix.CreateScale(_screenScale);
  spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, scaleMatrix * camera.GetMatrix());
    //Drawing the cursor
    spriteBatch.Draw(CursorSprite, CursorPosition, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
  spriteBatch.End();


texts: SMAPI add warp to existing map [Stardew Valley]

texts:
I am trying to add a warp into the existing farm map using SMAPI.
I tried the following things but both didn't work.

Setting the Warp inside the map properties:

Map farm = Game1.getLocationFromName("Farm").Map;
farm.Properties.TryGetValue("Warp", out PropertyValue initialWarps);
farm.Properties.Remove("Warp");
farm.Properties.Add("Warp", initialWarps + "64 18 TestRoom 5 5");

Setting the Warp inside a Tile:

Game1.currentLocation.setTileProperty(64, 18, "Back", "Warp", "64 18 TestRoom 5 5");

I can confirm that the first approach works when you set the Warp property directly in the map file but it doesn't seem to work if you add it afterwards.


texts:
I'm looking  to make a post request with a base64 image. When I make the request, I get an error called "ERROR_IMAGE_SIZE_0"

  import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.*;
import java.util.Base64;

public class Main {

    public static void main(String args[]) throws IOException {
        File originalFile = new File("sec_token.php.png");
        String encodedBase64 = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
            byte[] bytes = new byte[(int)originalFile.length()];
            fileInputStreamReader.read(bytes);
            encodedBase64 = new String(Base64.getEncoder().encodeToString(bytes));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(encodedBase64);
        HttpURLConnection con = (HttpURLConnection) new URL("http://2captcha.com/in.php?key=61f5d7a6cccc2db4e7c503a59f4f7e&method=base64&imginstructions="+encodedBase64).openConnection();

        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0";
        System.out.println("User agent: " + USER_AGENT);
        //add request header
        con.setRequestMethod("POST");
        con.setRequestProperty("Host", "2captcha.com");

        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = in.readLine()) != null){
            response.append(inputLine);
        }
        String res = response.toString();
        System.out.println(res);
    }
}


texts:
Is there something I'm not seeing or there is a flow in this algorithm(which everyone is referring to)
http://www.mine-control.com/zack/timesync/timesync.html

Assumption 1: When I say a is substracted from b it means "b - a", maybe in the text they actually meant the other way arround? I would guess so.
Assumption 2: the synchronization is to get the server clock on the client - If this is the gase shouldn't latency from server to client suffice?

Anyway, he article says:
Client sends packet with timestamp t1, Server responds with it's timestamp t2. Client receves this packet at t3. So t3 > t2 > t1

RTT = t1 - t3  (gives a negative value, I guess it should be t3 - t1)
latency = RTT / 2    (more or less, again it shoul be positive)
client server time delta = t2 - t3    (server timestamp - current time)
clock delta = t2 - t3 + RTT/2 (again, gives a negative value, abs again?)

Surely this cannot be... if the client time to server time is the same as the client thrn the clock delta is the RTT or 0 if I do abs (t2 -t3) + RTT/2.

if it is latencies are asymetric then the las calculation gives different results depending where I put abs
abs(t2 - t3) + RTT/2
abs(t2 - t3) +  abs (RTT/2)
t2 - t3 + abs(RTT/2)


texts: Forward A-star pathfinding vs Reverse A-star pathfinding

texts: Under what condition does doing Forward path finding or Reverse pathfinding get better result? Most tutorials for open grid tower defence games says to pathfind from the Goal to the monster. Why is it so?


texts: Skeletal animation: unexpected quarternion values

texts:
I'm following ThinMatrix's skeletal animation tutorial and his custom written Collada parser is deriving a different rotation quaternion from each keyframe matrix than the Assimp importer library does. They are close, except the values are signed inversely and unpredicatbly.

I dug around his importer code but it's a mess. I assume he is manually performing an additional axis calculation somewhere, any ideas what it could be and why?

Original Matrix

1 0 0 0
0 -0.06466547 -0.997907 0
0 0.997907 -0.06466556 3.810999
0 0 0 1

Assimp rotation quaternion : (0.7296115 , 0 , 0 , 0.683862)

ThinMatrix's rotation quaternion : -0.72961134 , 0, 0 , 0.68386203)

And for reference, the position vec3: (0, 0, 3.810999)

Update:

With an identity matrix both Assimp and the ThinMatrix code produce (0, 0, 0, 1)


texts: How to generate slopes that meet the plane, is using collision detection a good idea?

texts:
I have a terrain, which is defined by mesh. And there are a lot of other polygonal faces scattered throughout the terrain, they can be located above, or below or cutting through the terrain. You can think of those faces as platforms.

A screenshot below should clarify what I mean. Despite looking smooth, all the mesh are actually consist of small elements (number> 10k) combined together, giving the false appearance of smoothness. The obvious disconnected area are platforms.

My question is, how can I generate slopes that connect between the platforms and other platforms/ terrain? The slope plane is defined as a series of piecemeal planes, starting from the edge of platforms, going down or up, depending on where is the nearest platforms or terrain elements.

I would need to generate he slope planes so that I can compute the volume difference between the slopes and the terrains, it's not just for visualization purpose.

I'm thinking about using collision detection engines to do things like this, but

I'm not too sure whether this is the right idea
if this was the right idea, any open source collision detection engines ( C or C++ or C#) I can use?

Edit: Any open source framework that can do this is desired.


texts:
I am trying to make a jump function.

I am making a game in html5 canvas with Javascript. I have gotten the player to move. When making the jump function I decided to use a timeout to reverse the coordinates back to the original after a set time.

The error is after the character moves up he does not return to the original position the character just stays there, and then  upon clicking the jump (arrow key) again the player goes the other way e.g (down).

class Character {
  constructor() {
    this.x = 50;
    this.y = 400;
    this.posX = 0;
    this.posY = 0;
    this.width;
    this.height;
    this.hitPoints = 1;
    this.directionFace = "right";
    this.jump = false;
    this.jumpHeight = 23;
  }

  move(e) {
    this.x += this.posX;
    this.y += this.posY;

    if (e.keyCode == 37) {
      console.log('left');
      this.posX -= 10;
    }
    else if (e.keyCode == 38) {
      console.log("UP");

      if (!this.jumping) {
        this.posY -= this.jumpHeight;
        this.jumping = true;

        setTimeout(function() {
          this.posY = this.jumpHeight;
          this.jumping = false;
        }, 500);
      }
    }
    else if (e.keyCode == 39) {
      console.log("right");
      this.posX += 10;
    }
    e.preventDefault();
  }
}


texts:
Let's think for a moment a game where you'll have around 1k npcs, each one has to take its own decisions. Should each one has an object that decides what to do, or maybe exist one to process every unit?

Also, let's think about a complex ai, not just check if npc can see the player nor decides if npc will attack or not. Something like Dwarf Fortress does.


texts: How to make switch work with enum? C# Unity

texts:
I'm working on a script to fade UI elements in Unity, similar to a selector, where you can select the type of fading, and duration, and image to fade

I found that enum is the best option to achieve that result, but I have a problem, when I run the code only element of the enum work and the other don't, no matter if I use switchor if just the first statement run, I don't know what's wrong with the code

Please explain your answer
Please explain why the code is wrong
Please give feedback on how to improve

I'm using Unity version 5.3.5f1 and Visual Studio Community 2015

Goal

Make the enum work properly using either switch or if
Be able to use the variables inside the FadeOperations class to make
the calculations inside the Test class
Select from an array the type of desired operation
Select an UI element from Heriarchy and fade it

Steps

Create new Unity project (2D or 3D)
Create UI Image
Create Empty game object
Create new C# script (I called it Test)
Attach new script to empty game object

Code

Here's my code so far...

using UnityEngine;
using UnityEngine.UI;

 public enum FadeManager
 {
     fadeIn,
     fadeOut
 };

 [System.Serializable]
 public class FadeOperations
 {
     [Tooltip("Type of fading")]
     public FadeManager fadeType;

     [Tooltip("Duration time of the fading")]
     public float duration;

     [Tooltip("Select the image to fade")]
     public Image fadeImage;
 }

 public class Test : MonoBehaviour
 {
     [Tooltip("Select your type of fade")]
     public FadeOperations[] fadeOperations;

     //Reference to the class FadeOperations
     private FadeOperations _fo = new FadeOperations();

     //Loop for debug
     private void Update()
     {
         switch (_fo.fadeType)
         {
             Debug.Log(_fo.fadeType)
             //This statement works
             case FadeManager.fadeIn:
                 Debug.Log("Fadein"); //Only this piece of code works
                 break;

             //This statement doesn't work
             case FadeManager.fadeOut:
                 Debug.Log("Fadeout");
                 break;
         }
      }
  }

The result of the Log (_fo.fadeType) before the switch

fadeIn
UnityEngine.Debug:Log(Object)
Test:Start() (at Assets/_Scripts/Test.cs:34)


texts: Unity - Bullet spawns in wrong position in client

texts:
I am making a multiplayer game with prefab shooting, but unfortunately the prefab  sometimes spawns in the wrong position when I shoot from a client. The bullet tends to spawn in a location where the player was a few miliseconds ago, making that the bullet sometimes spawns inside of the player which killing the player in the process.

For shooting, I currently have this code setup to instantiate the bullet

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        float angle = GetComponentInChildren<Weapon>().angle;
        CmdShootBullet(angle);
        rigidbody.AddForce(Quaternion.AngleAxis(angle + 180, Vector3.forward) * Vector3.right * (bulletPrefab.GetComponent<Bullet>().force / 7.5f));
    }
}

[Command]
void CmdShootBullet (float angle) {
    GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
    Bullet bulletScript = bullet.GetComponent<Bullet>();
    bulletScript.shotBy = gameObject;
    bullet.GetComponent<Rigidbody>().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right * bulletScript.force);
    NetworkServer.Spawn(bullet);
}

And this is the setup for the location of the player and the gun. The top one is the player, the bottom is the gun.

My guess is that it has to do with lag, that the player position does not update soon enough, so how would I make it that the bullet spawns in the position of the player in the client rather than the position of the player in the host?


texts:
I have a grid based game. The main map is 2d array with land ids, something like this (here are 2 lands on the map, one formed where the 1's are and one formed by where the 2's are):

[ 1 , 2 , 2 ]
[ 1 , 1 , 2 ]
[ 1 , 2 , 2 ]

I want to draw buildings on the center of each land. But how is better to calculate the center? Just calculating mean(X),mean(Y) does not work - lands can bee narrow or have dumbbell shape.


texts: How to draw multiple large background images using libgdx?

texts:
I have developed a basic lunar lander-style game using Slick2D and dyn4j and am now redeveloping it using libgx for various reasons.  I am having problems drawing the background (i.e. everything, but the main spaceship) using libgdx and am not sure if I am doing this correctly.

In the Slick2D version of the game I have 3 layers to the background, which are all 4096 by 1440 pixel Image objects (this to allow for suffient variety in layers 2 and 3 as per below).  The layers are:

Layer 1 = stars (black background, with white pixels that vary in
brightness so that they appear to twinkle)
Layer 2 = mountains (black
background with deep blue filled landscape) (static image)
Layer 3 =
foreground (black background with foreground landscape, a simple line
drawing, with landing sites that vary in brightness over time)

I map where the ship (and therefore the screen) sits within the background images and then extract portions of the images to paint on the screen (this allows for wrapping across the top, the sides or the corners of the background images (note only the stars wrap across the top/bottom – the mountains and foreground only need to wrap side-to-side and across corners).  I then extract a portion of the image using the getSubImage() method and draw this to the screen using the draw() method, e.g. as follows:

stars.getImage().getSubImage(x1, y1, width, height).draw(0, 0);

In separate method calls in each update() loop I update the star and foreground images so that the stars and landing sites vary in intensity.  This is done by drawing directly to the background Images.

Using this approach the game performs at over 400FPS using Slick2D and dyn4j if I allow it to run unrestricted.

In the libgdx version I have created the backgrounds as Pixmap objects and then extracted portions by drawing a subsection to a new Pixmap object, which is the same size as the screen.  I then convert this to a Texture and draw it to the screen using a SpriteBatch.  Having read the documentation, it seems like this might be a very inefficient way to do things and, in practice, is too slow using just the star background (layer 1) without either of the other two layers.

There doesn’t appear to be a way to do this using Textures since I want to be able to draw to these to vary star and landing site intensity over time (unless I fundamentally re-write the game and use Sprites to draw the flashing stars and landing sites and just use a flat, static background Texture for everything else...)

So, my question is what is the correct way to do this using libgdx so that I get an effective level of performance?  Can I replicate the logic that I have used in the Slick2D version of the game or do I need to do a fundamental re-think?

Note the game is designed for the desktop only and is not intended to be run an Android or iOS.


texts:
In a sol system 2d simulation I have some problems in showing the entire system (ie: eaven planets far away than saturn )
letting distinguibles the nearest planet orbits.

Actualy a use a simple scaling logic like this

    double _x = W / 2.0 + ((x ) / maxW) * W;
    double _y = H / 2.0 + ((y ) / maxH) * H;

where
x is real planet x position (assuming sun at origin (0,0))
y is real planet y position
W is canvas width (i.e 512)
H is canvas height (i.e 512)

maxW and maxH are the system real border (or the portion I decide to simulate) : in the example I put
maxW = maxH = 20.0 * 149597870700.0; (20 times the sun earth distance)

What I ask : there's a methot to calculate a (non linear) scaling that let show a bigger portion of the system but keeping some distance
between objects near the center ?

EDIT: Here what I get if I enlarge the system borders:
maxW = maxH = 60.0 * 149597870700.0; (60 times the sun earth distance(UA) )


texts: What is the equivalent node in UE4 for Blender's Musgrave Node?

texts:
I'm trying to recreate Poliigon's non-tiling nodes https://www.youtube.com/watch?v=-VgtSL5ZpYc, in UE4, and the only thing so far I don't see the equivalent to is the Musgrave node https://docs.blender.org/manual/en/latest/render/shader_nodes/textures/musgrave.html, though UE4 has Perlin 3D Noise nodes, I don't see octave control described here https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/ExpressionReference/Vector/index.html

Is there a way to accomplish this? I assume so, UE4 cannot not have it... unless they already have a non-tiling node function already, and I don't know about it.


texts: How to rotate a triangle to look at a point?

texts: Lets say I have a triangle defined by 3 vertices and a center point, how do I rotate the triangle so its normal is looking at a specified point?


texts:
I've been trying to fix the game loop in a real time (tick delay) MUD. I realized using Thread.Sleep would seem clunky when the user spammed commands through their choice of client (Zmud, etc) e.g. east;south;southwest would wait three move ticks and then output everything from the past couple rooms.

The game loop basically calls a Flush and Fill method for each socket during each tick (50ms)

private void DoLoop()
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    while (running)
    {
        // for each socket, flush and fill
        ConnectionMonitor.Update();

        stopWatch.Stop();
        WaitIfNeeded(stopWatch.ElapsedMilliseconds);
        stopWatch.Reset();
    }
}

The Fill method fires the command events, but as mentioned before, they currently block using Thread.Sleep.

I tried adding a "ready" flag to the state object that attempts to execute the command along with a queue of spammed commands, but it ends up executing one command and queuing up the rest i.e. each subsequent command executes something that got queued up that should've been executed before. I must be missing something about the timer.

private readonly Queue<SpammedCommand> queuedCommands = new Queue<SpammedCommand>();
private bool ready = true;

private void TryExecuteCommand(string input)
{
    var commandContext = CommandContext.Create(input);
    var player = Server.Current.Database.Get<Player>(Session.Player.Key);
    var commandInfo = Server.Current.CommandLookup
        .FindCommand(commandContext.CommandName, player.IsAdmin);

    if (commandInfo != null)
    {
        if (!ready)
        {
            // queue command
            queuedCommands.Enqueue(new SpammedCommand()
                {
                    Context = commandContext,
                    Info = commandInfo
                });
            return;
        }

        if (queuedCommands.Count > 0)
        {
            // queue the incoming command
            queuedCommands.Enqueue(new SpammedCommand()
                {
                    Context = commandContext,
                    Info = commandInfo,
                });

            // dequeue and execute
            var command = queuedCommands.Dequeue();
            command.Info.Command.Execute(Session, command.Context);
            setTimeout(command.Info.TickLength);
            return;
        }
        commandInfo.Command.Execute(Session, commandContext);
        setTimeout(commandInfo.TickLength);
    }
    else
    {
        Session.WriteLine("Command not recognized");
    }
}

Finally, setTimeout was supposed to set the execution delay (TickLength) for that command, and makeReady just sets the ready flag on the state object to true.

private void setTimeout(TickDelay tickDelay)
{
    ready = false;
    var t = new System.Timers.Timer()
        {
            Interval = (long) tickDelay,
            AutoReset = false,
        };

    t.Elapsed += makeReady;
    t.Start(); // fire this in tickDelay ms
}

// MAKE READYYYYY!!!!
private void makeReady(object sender, System.Timers.ElapsedEventArgs e)
{
    ready = true;
}

Am I missing something about the System.Timers.Timer created in setTimeout? How can I execute (and output) spammed commands per TickLength without using Thread.Sleep?


texts: How can I calculate the angle and proper turn direction between two 2D vectors?

texts:
I am working on some movement AI where there are no obstacles and movement is restricted to the XY plane. I am calculating two vectors, v, the facing direction of ship 1, and w, the vector pointing from the position of ship 1 to ship 2.

I am then calculating the angle between these two vectors using the formula

arccos((v · w) / (|v| · |w|))

The problem I'm having is that arccos only returns values between 0° and 180°.  This makes it impossible to determine whether I should turn left or right to face the other ship.

Is there a better way to do this?


texts:
Hi I recently created a javascript game, in this game, math random is used to pick a random shape.
The shapes are in strings, and the associated numbers within the string are then used to show a color.
Is there any way to replace the simple hex colors with an image?
For example:
else if (shape === "H"){
    return [[8,8,8],
            [8,8,8],
            [8,8,8]];

The "8" ties into the following string to get the #F10B38 color.
const color = [null,"#FF2D00","#FF9300","#51FF00","#00FF93","#0087FF","#4E49A7","#9649A7","#F10B38"];


texts: How to Capture Vive's USB-Audio Data from Playback Devices

texts:
I am developing a music visualizer software for Vive so I am trying to get FFT data from music that users listen to. However, I couldn't take any data from USB audio devices versus my soundcard.

What I have done is

Using FMOD, I could access recording devices but there is no usb-audio device in the recording device list so I can only access the speaker(What U Hear)

  system->recordStart(0, sound, true); // only I can capture data from recording devices
  system->playSound(FMOD_CHANNEL_FREE,
  sound, false, &channel);

Using WASAPI in Windows SDK, I tried to get the data although It also takes only data from the speaker not USB-Audio.
I am not sure I did correct here but the SDK's example, WASAPICaptureSharedTimerDriven, doesn't seem to work for USB-AUDIO but it works fine with data from my soundcard (What U Hear)

If anyone has captured any audio data through USB-audio, please tell me the approach.


texts: Can I implement allocation-free time releated event scheduler via pure C#?

texts:
I read some article about a gameloop, based on Actor system. (yes, it is Development & Deployment of Multiplayer    Online Games Vol.2 by 'No Bugs' Hare)

Here is pseudocode.

while(true) {
    wait_for_event();
    read_and_process_inputs();
    update();
    post_updates_to_clients();
    post_timer_event(time_left_until_end_of_network_tick);
}

It has post_timer_event() instead of thread sleep method. I want to know that is it possible to implement like this by using pure C#? especially, without any memory-allocation or performance issue. If it is possible, I want to know how implement it (or ideas, keywords for googling).

Thanks.


texts:
Hello I'm using SDL with C++ and I got this code:

void handleEvents() {
    SDL_Finger* finger = SDL_GetTouchFinger(SDL_GetTouchDevice(0), 0);
}

I do not know what SDL does inside the GetTouch function, maybe it allocates memory. Do I have to "destroy" finger here? Or will it be deleted by the end of the methods scope?
Thank you.


texts:
So I created a Hex Sphere using Houdini and exported it as FBX to Maya where I created UV's for the model to use it in Unity

This is how my sphere looks inside Unity

All the hexes are separated so they act like individual gameobjects in Unity. Now I created the below texture in form of a Hex in Photoshop which looks like below

When I tried to map it inside Unity with an x-tiling of 10 and y-tiling of 12, it doesn't look right

The texturing is completely out of place. What am I doing wrong? Can this be fixed within Unity itself or do I have to go back to Maya and fix the UV's there? This could be a simple issue that could be fixed I suppose but I am not an Artist and I don't exactly know what the problem is so please help me out :)


texts:
I am working on a 2D top-view grid-based game. A ball that rolls on the grid made up of different tiles. The tiles interact with the ball in a variety of ways.

I am having difficulty cleanly implementing the turning tile. The image below represents a single tile in the grid, which turns the ball by a right angle.

If the ball rolls in from the bottom, it smoothly changes direction and rolls to the right. If it rolls in from the right, it is turned smoothly to the bottom. If the ball rolls in from top or left, its trajectory remains unchanged by the tile.

The tile shouldn't change the magnitude of the velocity of the ball - only change its direction.

The ball has Velocity and Position vectors, and the tile has Position and Dimension vectors.

I have already implemented this, but the code is messy and buggy. What is an elegant way to achieve this, preferably by modification of the ball's Velocity vector by a formula?


texts: How to reset a gameobject to it's prefab condition?

texts:
I have a GameObject with a ragdoll in it. Gameobject comes from a prefab which is pooled. So whenever the enemy is killed it's disabled then enabled when spawn.

Problem is that the ragdoll settings and it's condition cannot be reset by enabling.  i.e. enemy stays dead even though respawned.
Is there a way to easily reset a GameObject to prefab state?

Solution online is to keep all the transforms and re-apply them by code. Is this the only way?


texts: Problem with modifying dice in another players turn

texts: I have the following problem: I want to create a multiplayer game where each player has a turn where he has to roll a lot of dice again and again. But the other players are capable of modifying each single dice with a special action. But since this is a rare action because each player has a limited amount of modifications, I do not want to implement a simple dialog where you have to approve each roll. This would make the game rather sluggish. Any suggestions for the best way to implement a UI which allows to modify every single dice, but makes the game as fast as possible?


texts: How to send data from compute shader to vertex shader

texts:
I have some shaders, every shader has the same constant buffer,

//-----------------------
//constant buffer
//---------------------
cbuffer cbPerFrame : register(b0)
{
    float3 gEyePosW;
    float4x4 gView;
    float4x4 gProj;
    float gDim;
    float3 gVoxelOffset;
    float gVoxelSize;
};

I think it's a waste to send these same constant buffer several times, so I want to pack them in one Constant Buffer, and share them to other vertex shaders.

I have tried send constant buffer to compute shader, but they don't work in vertex shader.

Do I need to pack these data in one structured buffer? Is it faster than send constant buffer several times?

Is deferred shading relevant to this problem? Which solution do we usually use to solve this problem?


texts: Calculating impulse propagation through a rigid body after a collision

texts:
I'm working on a game. I need to work out what the impulse is at different points on a body as a result of a collision.

For example, in the following diagram, if there is a collision that results in an impulse being applied to the body at A, what will the resulting impulse be at B? I know the mass, center of mass and dimensions of the body.


texts: Procedurally generated terrain that has some caves

texts:
I want to generate a terrain that has a few overhangs, and some caves.
So a simple height field from a 2D noise is out, as there would be no overhangs.

The other extreme, to define a world from a 3D noise field (I typically use marching cubes over a noise field) results in a wildly chaotic terrain.

What would be a good compromise between these two?

Something that produces mostly hills (like a height field), yet exhibits the occasional overhang/cave?

I've added a bias towards 'air' at high altitude, and a bias towards 'dirt' at low altitude, but that only helps me so far. It looks a bit better, but still too alien to be a real terrain.

Any quick hacks I can try, without actually having to simulate gravity, geology, and weather systems?


texts: Check if OpenVR / SteamVR / OculusVR headset is mounted on your head

texts:
The Oculus and the Vive have this light proximity sensor that detects whether you have your VR headset placed on your head currently or not.

Is there any way to tap into that for our own game checks? E.g. We could pause or restart the game depending on whether the headset's being worn or not.

I'm using Unity/C#, but any (driver / API level) help is much appreciated.


texts: How do you partition a level and create screen transitions out of these partitions?

texts:
The levels in Castlevania games, you walk forward and then come to a point on the level where the screen stops scrolling but is not a deadend and there's no door either. They just wanted to transition to the next room for some reason (like a hallway transitioning to another room).

I want to create something like this in Unity, using 2.5d (3d characters constrained in 2d plane); question is, do I separate each transition to a scene? But that seems kinda wasteful (I don't know, maybe). Or just one scene and develop the level as a whole and do some camera programming for the transition making sure everything lines up?


texts: Microphone channel not detected in Unity

texts:
This is very specific to Unity.

A few testers are reporting that their microphone output isn't being detected. The code below works for the vast majority of users, but certain microphones seem to be outputting on the wrong channel (R maybe)?

 AudioClip current_microphone_recording_clip = Microphone.Start(microphone_name, true, 30, 16000);

How can I capture and analyze output from several channels? I don't see any channels parameter for Microphone.Start


texts: Can I use PARSE for creating turned based Game?

texts:
I am working on creating a Turned - Based game similar to "Draw Something". I want to replace the Game Center feature with my own server using PARSE. Replace in terms of all game logic like Match making, Notifying Turns etc in PARSE Server. I have used PARSE to create app like similar to Instagram where user will have their account and they do stuff within. However I am wondering if I can put logic of match making in PARSE Server to get match for any of player. More of features of Game Center might needed to be build in PARSE Server.

Kindly let me know any suggestions if anyone has used PARSE as Game Server. Thanks in Advance.


texts: Is it good to use 24 fps animation in 60 fps game?

texts: Is it normal to use 24 fps animation in 60 fps game or it will hurt perfomance or create bugs?


texts: Sharing game code between client and server

texts:
I'm having a code design problem involving synchronization between the server and clients. I have a class GameWorld that handles all of the simulation details (positions, velocities, projectiles, what have you) that exists in two places:

on the server, it is contained in the class GameRoom which handles all of the players connected to a specific lobby, reads and sends messages.
on the client, it's in the class GameplayGameState (using the stack of states pattern).

The problem is that i want to include the simulation code in this single GameWorld class to avoid the various bugs involved in duplicating the code in both sides (maybe i change something in one but forget to do the same in the other). However, there is one thing that needs to change between the two: on the server, GameWorld needs to notify GameRoom somehow about events (like "this player died", "this player shot in that direction"), so that GameRoom can then broadcast the event to the clients. On the client, however, i need no such thing, but i do need a way for GameWorld to handle similar events for other reasons (for example, a dying player doesn't need to notify any clients but it does need to play a sound or display a message or something).

Programmatically, how would I go about implementing different behaviors for different sides? Keep in mind the code for GameWorld is separate and can't have ANY knowledge of its outside overlords. How can two different programs get the information they need without GameWorld knowing what to give them? keep in mind polling is off the table, because it would be ridiculously inefficient to scan the GameWorld every tick for changes, keeping the previous state for reference. GameWorld itself needs to generate the events.


texts: What would be the easiest way to define actions of multiple buttons

texts: So I'm creating a game that involves lots of different areas that involve pushing buttons to do certain things.  Anyway, I'm trying to figure out how to let each button do its own separate thing, like open a door or things like that.  I already know how to setup a Raycast between the player's mouse to the button, but now I'm just figuring out how to make each button trigger a separate action.  Basically, should I set up a new tag for each button?  Or create different scripts, even?  I haven't tried anything yet and I need help.  Thanks :D


texts:
I have issues with constant buffer member alignments.
I have the following C++ struct:
namespace Renderer {
    using DirectX::SimpleMath::Matrix;
    using DirectX::SimpleMath::Vector3;
    using DirectX::SimpleMath::Vector2;
    struct alignas(16) CCameraMatrixBuffer
    {
        Matrix ViewProjection;
        //--
        Matrix View;
        //--
        Matrix Projection;
        //--
        Vector3 CamPositionWS;
        int CameraUnderwater;
        //--
        Vector3 CamDirectionWS;
        unsigned int RoomNumber;
        //--
        Vector2 ViewSize;
        Vector2 InvViewSize;
        //--
        unsigned int Frame;
        //--

    };
}

and this HLSL counterpart:
    cbuffer CameraMatrixBuffer : register(b0)
{
    float4x4 ViewProjection;
    float4x4 View;
    float4x4 Projection;
    float3 CamPositionWS;
    int CameraUnderwater;
    float3 CamDirectionWS;
    unsigned int RoomNumber;
    float2 ViewSize;
    float2 InvViewSize;
    unsigned int Frame;
};

however, when i debug the shader, CamDirectionWS shows the following:

The 1024.000f is part of the ViewSize (the resolution).
Can someone tell me whats wrong with it?


texts: How to draw only visible models of the game?

texts:
Suppose I have an array of models, each having it’s own “position” in the world space (scale*translation matrix). And I have an orthogonal camera. How can I test if model is “visible”, i.e. is in the range of the camera? Like this:

        +--------------+
        |              |
xxxxxxxx|xxxxxxxxxxxxxx|xxxxxxxxx
        |              |
        +--------------+

I want to know whether x is in a frame or not. Thank you very much in advance, I know it should be a fairly simple (if not trivial) task :)


texts: How do I make my game (without performance problems) not stutter?

texts:
I've made a game that has gameticks every 1/60 seconds. These gameticks take very little time to calculate (< 0.5 ms).

The game is written in Javascript and uses requestAnimationFrame (rAF). rAF fires roughly a few milliseconds (how many is determined by what the browser thinks is necessary) before (mostly) every frame output to the monitor.

The code does the following every rAF:

get a timestamp
figure out how many gameticks should have happened at that timestamp, and (if needed) run enough to catch up
render state after latest gametick to screen

This works fine most of the time. It runs at a consistent 60 gameticks/second, regardless of what the screen is doing (good for syncing multiplayer). It handles any framerate. The game looks smooth except, sometimes, the timestamps happen to be right around the boundary for new gameticks.

frame 10: gametick 2.01 (renders gametick 2)
frame 11: gametick 2.99 (renders gametick 2)
frame 12: gametick 4.01 (renders gametick 4)
frame 13: gametick 4.99 (renders gametick 4)
frame 14: gametick 6.01 (renders gametick 6)

When this happens, it stutters horribly. How do I make it avoid stuttering needlessly?


texts: Disadvantages of using multiple versions of OpenGL in LWJGL?

texts:
So, I'm trying to figure out LWJGL, and my goal is to use OpenGL 3.2 (because pretty shaders are pretty).  But in every tutorial I can find for LWJGL, they import a bunch of different OpenGL versions and use them at the same time.  For example, this one imports GL11, GL15, GL20, and GL30 and uses functions from all of them.  This seems intuitively like it would be messy and generally a bad idea.  Besides the normal disadvantages of using deprecated functions, is there any particular reason not to do this?  Could it affect performance in any way?  Is there a potential for errors and odd behavior to occur?

Also, if possible, does anyone have an example of LWJGL written only using GL32?  I've found C++ code samples that do this, but I'm not too familiar with C++, so it's difficult for me to translate.


texts:
I'm making a story-intensive game (RPG) for the iPhone and want to distribute it over the AppStore. But AppStore Apps have the potential to be distributed internationally, so I need kind of legal advice - maybe someone of the independent developers here was already in a similiar situation.

I'm planning to use an book (i.e. classic literature, world literature or fairytales) as foundation for the storyline of my game: So what are the basic conditions, if I dont want to run into big problems? I heard about 70 years after first publishing (or after death of the author?) a book would be "out of copyright" - but is that true for every country? Could I get problems in the App Store?

My Background: It doesn't seem economical to pay a scenario writer for my game (no budget) - and myself isn't "talented" so much in this field. But there are already tons of great stories out there, which never get a game release so far. Because of that, I was thinking: "Why not use this, instead of making a crap story by myself"...

I know that I can't get here a reply from a lawyer - but I hope for tips from other independent developers with experience in such cases...)


texts:
Whats the usual way to control a player in a top down game? We have to look in the direction of the mouse cause the player hold a torch.

My first try was:

to to make it absolute like W move to screen top, A left, D right, S bottom... But it feels a kind of strange.
second try was to make it relative to the player. So W is always straight forward, A and D is moving sideway and S is backwards. But i heard of my tester thats very hard.

So whats the better / right way for the movement in a top down game in that you can move in a another direction as you look?


texts: Side detection on Rectangle collision detection?

texts:
How can I determine which of the sides on a Rectangle that was hit by another Rectangle (or Circle if that's easier)?

I originally tried creating 8 subrectangles for my main rectangle - one for each side and corner - with the appropriate length and width of one pixel. This didn't work out very well though, to my understanding it was thwarted by the speed and update frequency...

Any thoughts?


texts: iOS cocos2d - sprite gets stuck in collision detection

texts:
I'm developing a top down game in cocos2d and I have collision code that checks collisions between enemies and the player so that they don't go through each other. The code seems to work but the problem is that when one of the enemies colides with an enemy or the player then they just freeze and don't continue their movement. Any help would be appreciated.

Collision detection between enemies:

-(void)checkCollisionWithPosition:(CGPoint)position OldPos:(CGPoint)oldPos tileMap:(CCTMXTiledMap *)map andLayer:(CCTMXLayer *)metaLayer andEnemies:(NSArray *)enemies {
CGPoint tileCoord = [self tileCoordForPosition:position withMap:map];
int tileGrid = [metaLayer tileGIDAt:tileCoord];
if (tileGrid) {
    NSDictionary *properties = [map propertiesForGID:tileGrid];
    if (properties) {
        NSString *collision = [properties valueForKey:@"Colidable"];
        if (collision && [collision compare:@"True"] == NSOrderedSame) {
            self.position = oldPos;
            [self changeStateWithState:enemIdle];
            //[self setViewpointCenter:player.position];
            return;
        }
    }
}

for (BasicEnemy *enemy in enemies) {
    if (enemy != self && CGRectIntersectsRect([enemy boundingBox], [self boundingBox]) && CGPointEqualToPoint(_facingDir, [enemy getDirectionInRelationToPlayer:enemy.position])) {
        self.position = oldPos;

        return;
    }
}

self.position = position;
}


texts: Can you develop a game in XNA only on Windows for the Xbox 360?

texts:
I'm going to start developing a game for the Xbox 360, its a small homebrew development and I don't have an Xbox 360 yet. Is it possible for me to develop the entire game targeting the XNA framework on Windows, and lastly "Create Copy of Project for Xbox 360" and have it work flawlessly?

What are the issues I would run into? Why do you recommend targeting and deploying to the Xbox 360 during development? and do I really need an Xbox 360 during development?

I'm also planning on using the superbly built Torque X game engine. Would this work well on my PC alone as well? And then transition over to the Xbox 360 without changing much code?


texts: Why does my character stop a little before landing on the ground?

texts:
I made a little game with side-scrolling and a box (the player) jumping across the level. The simple physics are almost done, but I have two problem with the way things behave:

On landing, the box takes a little time to reach the floor
When the box hit a roof, there is always a little space between it and the object.

Here is my collision code (in the player's Step Event):

myGravity = 0.5;
if (vspeed > 10)  vspeed = 10;

speedAir = abs(vspeed+1);

//ON_FLOOR = !(place_free(x, y + speedAir));
ON_AIR = place_free(x, y + speedAir);

FREE_RIGHT = place_free(x + speedScreen, y);
FREE_UP = place_free(x, y - speedAir);

KEY_UP = keyboard_check(vk_up);
KEY_LEFT = keyboard_check(vk_left);
KEY_RIGHT = keyboard_check(vk_right);
KEY_FIRE = keyboard_check(vk_space);

/* JUMP */
if ON_AIR
{
    gravity = myGravity;
    gravity_direction = 270;

    if !(FREE_UP)
    {
        vspeed = 0;
    }
}

else // if ON_FLOOR
{
    gravity = 0;
    gravity_direction = 270;
    vspeed = 0;

    // JUMP
    if KEY_UP & FREE_UP
    {
        vspeed = -10;
    }
}

/* LATERAL */
if (FREE_RIGHT)
{
    x += speedScreen; // screen side-scrolling
}

How can I do this correctly?


texts:
I'm developing a game using an entity-component system, and had a question about storing, using and linking textures to entities.

I have a GraphicsSystem that is responsible for storing and registering textures. Each entity has a GraphicsComponent including a textureID, which is just an integer used to look up the stored texture in the GraphicsSystem.

This works well for textures that are only used by one entity, for example player textures. In this case, I can create new GraphicsComponents by something like:

GraphicsComponent(graphicsSystem.addTexture("Player1.png"));

graphicsSystem.addTexture() adds a texture to the graphics system and returns an integer to its position, which is then stored in the component for later use.

My problem is that this approach doesn't work for textures that are registered once and then used across multiple entities. Examples are textures for bullets and world terrain.

My temporary solution to this problem is to register the texture once, and store the texture id centrally. Whenever I need to (for example) create a new bullet, I just need to remember that the bullet is texture id of (say) 1, and then pass this to the GraphicsComponent constructor for the bullet.

Similarly for my terrains, I currently just need to remember which texture ID is for which terrain type:

World::World() :    floorTerrain(1),
                    wallTerrain(2),
                    ...

I did think about storing these IDs somewhere, for example in the GraphicsSystem itself, but my world instance doesn't have direct access to the graphics system.

Anyway, as you can probably tell I am new to ECS game design and would appreciate any pointers!

Thanks,
Rich.


texts: Why does this raycast code give me a NullReferenceException?

texts:
The Error in the code is NullReferenceException: Object reference not set to an instance of an object for if (hitxx.collider.tag == "soldier")
Please help! Thanks in advance

 void Update () {
            Physics.Raycast (eyeenemy.transform.position, (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,out hitxx);

            Debug.DrawRay (eyeenemy.transform.position, (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,Color.green);
            if (hitxx.collider.tag == "soldier") {
                gameObject.transform.LookAt (soldier.transform.position);
                Debug.Log ("chuchu");
            }


texts: Unity 2D Hingejoints break under extreme force

texts:
I have added a rope to my game that is made up of multiple small gameobjects, each connected to eachother by a HingeJoint2D. Since 1 unit of mass in Unity is supposed to represent 1 kg, I've made the player's mass 60 (60kg). When the mass of each rope segment (of which there are 40) is 20, the rope supports the player when they jump off a cliff.

Now 20 kg per rope segment sounds ludicrous. However when I make each rope segment weigh 1 (1kg) the hingejoints break completely and jitter around crazily. The force of the 60kg player against the 1kg segments seems to be too much.

I would much rather have the rope be lighter, so it doesn't move the player when throwing and being dragged as much. Any suggestions on how to fix HingeJoint2D's and make them act, as you know, a joint should?
EDIT: Increasing the Position and Velocity Iterations in File->Project->Physics2D menu from the default 3 and 9 respectively, up to a whopping 40 fixes this problem. This is a massive increase. Unsure if performance will suffer too much with these new settings.


texts: How did you learn the DirectX 11 API? MSDN documentation, tutorials, blogs, sample applications, books, etc?


texts:
Is there a way to change actor texture without creating a new object?

I want to change my ImageButton texture when resize() is called, and for example for screen > 800px, ImageButton have bigger texture, and if screen <= 800px, ImageButton have smaller texture?

Now when I'm increasing my window size, ImageButton is scaling up but quality is bad so I want to load bigger texture.

Thank you for help.


texts:
I have just started using the Cocos2D library for Android. I am trying to make a walking bear animation.

For that I am using a CCSpriteFrameCache, but I'm getting a "frame not found" error in the log.

I have added an AnimBear.plist file and an AnimBear.png file (combined image of the various movements of the bear) to the assets folder.

My Java code is as per below :

CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames("AnimBear.plist");
CCSpriteSheet spriteSheet = CCSpriteSheet.spriteSheet("AnimBear.png");

scene.addChild(spriteSheet);

ArrayList<CCSpriteFrame> walkSprites = new ArrayList<CCSpriteFrame>();

for (int i = 1; i <= 8; ++i)
{
    walkSprites.add(CCSpriteFrameCache.sharedSpriteFrameCache().getSpriteFrame("bear" + i + ".png"));
    System.out.println("bear image is added");
}

CCAnimation walkAnimation = CCAnimation.animation("bear", 0.1f, walkSprites);

bear = CCSprite.sprite(walkSprites.get(0));

this.walkAction = CCRepeatForever.action(CCAnimate.action(walkAnimation, false));

bear.runAction(walkAction);

Now here are the errors I get:

  walkSprites.get(0) line throws a Null Pointer Exception.
  CCSpriteFrameCache.sharedSpriteFrameCache().getSpriteFrame("bear" + i + ".png") line prints "CCSpriteFrameCache: Frame '%s' not found" in the logcat

Can anybody help me please, what am I doing wrong?

Thanks in advance.


texts: Unity Hub 2.4.2 does not open a login window

texts:
I just installed Unity Hub 2.4.2 on my MacBook Pro 2015 running macOS Big Sur. However, when attempting to open a login window from the hub, it opens briefly and then quits. (The hub remains open, but the login window closes.)
I've already tried:

Quitting and reopening the hub
Uninstalling and reinstalling the hub

Are there any suggestions on how to fix this? Does anybody have the same problem?


texts: Was there any equivalent of glVertex3f in Direct3D?

texts: I know that OpenGL's Vertex3f is a bit old but I can't find any information about suitable equivalent for that function that was used in DirectX. Was there any equivalent in DX?


texts: Overload how an object instance of a class is treated when used

texts:
So I've made this struct that encapsulates a glm::vec4. This is because vec3s are treated as 16-byte in GLSL, but I don't want to assign a vec4 if I only really need 3 components. Anyway, my question isn't really OpenGL/GLSL specific, but since it is in this context it would be easier to post it here.

Below is my "overloaded vec3", and some code for how I use it:

struct GpuVec3
{
public:
    GpuVec3() {}

    GpuVec3& GpuVec3::operator=(const vec3& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = 1.0f;

        return *this;
    }

private:
    vec4 v;
};

// ...

// Struct using GpuVec3 members
struct Material
{
public:
    GpuVec3 Emissive;
    GpuVec3 Ambient;
    GpuVec3 Diffuse;
    GpuVec4 SpecularAndShininess;
};

// Assign vec3 to GpuVec3 (works fine)
material->Emissive = vec3(0.1f, 0.0f, 0.0f);

// ... initializing uniform block and stuff ...

// Passing Emissive to function that expects vec3 (doesn't work, of course)
// UniformBlock3fv(GLchar* uniformBlockName, GLchar* uniformName, glm::vec3 value)
program->UniformBlock3fv("uniMaterial", "Emissive", material->Emissive);

In the last line of code I want to be able to pass my GpuVec3 to a function that expects a vec3, this is not possible of course.

My question is, is there some way in C/C++ possible to overload how an object instance of a class is treated when used? A pseudo-code example below what I want to happen if I use my object:

if (material->Emissive is called) { return v.xyz; }


texts: Inifinite scrolling draggable background for a 2D editor

texts:
I need to create something like blender's Node Editor for my 2D editor. Now I am not sure how to create the background so it is static infinite and draggable simillar to blender.

I need to make it so it doesn't wreck my GPU and that its infinite and can be zoomed in and out without a problem

Can anyone give me tips on where to start?


texts: One scene or multiple scenes for levels?

texts: In my game there are multiple levels (300 levels) You start a level by clicking on it in the level map (like the one in candy crush etc) The levels will be having the same gameplay, character and environment but the items (stored as scriptableobjects) available and the winning criteria will be different. Now I am confused about something. Is it recommended that each level should have its own scene and script?


texts: Need an option to send camera output as video or frames in Unity3d 2017

texts:
Tools I've used in Unity 5.x are breaking my 2017 scene... and I do not see a way to output video or frames from Cinemachine (although I am trying to understand all of its features).

What is the best way in a mandatory C#/Unity 2017 workflow to capture camera output within Unity -- not a screen grab? No postprocessing needed... just frames!

In the past I have used Renderator Pro and VR Rocks, neither of which seem at the moment to support 2017 -- using deprecated code.

SOLUTION -- ROCK VR Does indeed work with Unity 2017... although not exactly the way I have modified it for 5.x.... but going back to stock import of resources and rebuilding works well.


texts: Would it be good idea to use blender to create sprite and animating rather than using a 2d software to create sprites and animating them in 2d

texts:
I'm making this 2d side scroller game. I had been working on 3d games(modelling and animation) for 2 years, thus my experience with 2d sprites is none to zero.

So I've been struggling with asset creation in 2d especially thinking about animation is kind of stressing me out. There will be a lot of fighting animation in the game and may be that I'm new to 2d it just feels impossible to create a character and animating it do lots of combos.

An idea poped into my mind, using blender to create animation and rendering the animation as png to create spritesheet. I'm not sure if that's already a thing, I've did some research and there are people who do recommend and there are those who don't. It just felt a bit vague.

So my question is, would using blender to create 2d sprites and their animations be easier, since I'm exprienced with it. Or should I try to handle  sprites in completely 2d?
side note: every character is gonna be plain black(like shadow)


texts:
I wanted to add a high score to my game but I don't know how I already tried to find some videos for it but I just can't find the right one. I already have a scoreUI on my game I just wanted to add a high score.

Here is my UIManager's script which consists of different functions including the score system.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class uiManager : MonoBehaviour {

public Button[] buttons;
public Text scoreText;
int score;
bool gameOver;

// Use this for initialization
void Start () {
    gameOver = false;
    score = 0;
    InvokeRepeating("scoreUpdate", 0.5f, 0.25f);
}

// Update is called once per frame
void Update () {
    scoreText.text = "" + score;
}

void scoreUpdate(){
    if (gameOver == false) {
        score += 1;
    }
}
public void gameOverActivated(){
    gameOver = true;
    foreach(Button button in buttons) {
        button.gameObject.SetActive(true);
    }
}

public void Play() {
    SceneManager.LoadScene("level1");
}

public void Menu(){
    SceneManager.LoadScene("Menu");
}

public void Retry()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

public void Pause() {

    if (Time.timeScale == 1) {
        Time.timeScale = 0;
    }
    else if (Time.timeScale == 0) {
        Time.timeScale = 1;
    }
}
}

I got the score system from Charger Games. Here is the link to the Video

and here is what my game looks like


texts: How can I identify loaded models so I can efficiently avoid loading them twice?

texts:
I'm making a fairly basic OpenGL 3D engine, at the moment. In this engine, when you load an object, you would write

manager->LoadObjFile("cube.obj");
manager->AddParent("uvmap.bmp", "cube.obj", "cube", glm::vec3(10.0f, 1.0f, 0.0f));

"uvmap.bmp" being the texture, "cube.obj" is the .obj file path, "cube" being the ID for the object.

My question is, at the moment, when it loads an object, it stores the object in a struct with all of the buffer data and an ID, the ID being the path of the obj file, so when I load an .obj, it runs through all of the already loaded files and compared the ID of each using strcmp, which obviously when there's thousands of items, is going to start to get a bit slow.... it does the same for AddParent, and most of my other methods (different vector of data than where the obj data is stored).

What would be best in terms of identifying items, an integer? I really don't know, I want this to be as high level, user friendly as possible, but want to keep it as optimized and as efficient as possible.


texts: How can I get my player's character to slide along a rail?

texts:
I am creating a snowboarding game and would like my player to be able to jump on a rail and move along it if it lands on it.

I have no idea how to approach this. I have already tried using ray casts and waypoints but nothing works. I need to make sure the player moves along the rail, from any point that the player jumps onto it: e.g. if they land in the middle of the rail they keep following its curve from that point. The rails are not straight and have curves on them.

How can I get my player to be able to jump on a curved rail like this, and start sliding from the point they jumped onto it?