texts:
I need some help with OpenGL textures masking. I have it working but need to find some other blending function parameters to work in other way.
Now I have:

//Background
...code...
    glBlendFunc(GL_ONE, GL_ZERO);
...code

//Mask
...code...
    glBlendFuncSeparate(GL_ZERO, GL_ONE, GL_DST_COLOR, GL_ZERO);
...code...

//Foreground
...code
    glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
...code

Now it sets foreground's opacity to 0 (fills with background texture) where mask is transparent. I need it to react to mask's colors. I mean something like setting foregrounds opacity depending on mask's color. For example if mask is black (0.0,0.0,0.0) then the opacity of that place in foreground is 0 (is filled with background), and if mask is white (1.0,1.0,1.0) then the opacity of foreground is 1 (not filled with background). It can be in reverse consequence (white = opacity 0, black = opacity 1). I just need it to work depending on color.

1st column is my current result. Circle in mask is transparent.
 2nd column is example of result I am trying to get. Circle in mask
    is white.
 3rd column is example of why I want to get it working just like as I
    said (white mask color = foreground alpha 0, black mask color =
    foreground alpha 1 or reverse)

1st row is background
 2nd row is mask
 3rd row is foreground
 4th row is result


texts: What does vertex:disp and tessellate:tessEdge mean? [Shader] [Unity]

texts:
I came across the following declaration on unity tutorial

#pragma surface surf BlinnPhong addshadow fullforwardshadows
vertex:disp tessellate:tessEdge nolightmap

I think disp is the displacement shader but what does vertex:disp mean?
Likewise for tesselate:tessEdge.

from https://docs.unity3d.com/Manual/SL-SurfaceShaderTessellation.html

Thanks. I am rather new to HLSL.


texts: Unity detecting edge of mesh or end of mesh

texts:
I'm trying to create procedurally generated tiles and I've reached a point where I need to figure out the boundaries of the mesh or the outer vertices of the mesh.

    RaycastHit hit;
    if (Physics.Raycast(bound[ i ].v2, Vector3.forward, out hit)) {
    if (hit.distance > 2) {

I've tried raycasting all the vertices, but still can't get the vertices of the edge. The mesh does have a collider. any help on how i would go about this is appreciated, Thanks.


texts: OpenGL drawing multiple polygons with different colors with VBOs

texts:
I'm trying to change my program to use VBOs instead of immediate rendering for performance reason. The rendering consists of thousands of hexagons, all of the same size/shape. Each hexagon has a different color, so I'm trying to figure out how to change the color of the VBO for each rendered hex. Here's the code I'm using right now:

private static final int NUM_VERTICES = 6;
private static final int VERTEX_SIZE = 2;
private static final int COLOR_SIZE = 3;

private int vboVertexHandle;
private int vboColorHandle;

// This is called once on initialization
private void initVbo() {
    DoubleBuffer vertexBuffer = BufferUtils.createDoubleBuffer(VERTEX_SIZE * NUM_VERTICES);
    FloatBuffer colorBuffer = BufferUtils.createFloatBuffer(COLOR_SIZE * NUM_VERTICES);
    for (Point vertex : WorldHandler.TILE_VERTICES) {
        vertexBuffer.put(new double[]{vertex.x(), vertex.y()});
        colorBuffer.put(new float[]{1f, 0f, 0f});
    }
    vertexBuffer.flip();
    colorBuffer.flip();

    vboVertexHandle = GL15.glGenBuffers();
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboVertexHandle);
    GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexBuffer, GL15.GL_STATIC_DRAW);
    GL30.glBindVertexArray(0);

    vboColorHandle = GL15.glGenBuffers();
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboColorHandle);
    GL15.glBufferData(GL15.GL_ARRAY_BUFFER, colorBuffer, GL15.GL_STATIC_DRAW);
    GL30.glBindVertexArray(0);
}

// This is called thousands of times per frame
private void drawHex(Color color) {
    // Set up the vertex buffer
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboVertexHandle);
    GL11.glVertexPointer(VERTEX_SIZE, GL11.GL_DOUBLE, 0, 0L);

    // Set up the color buffer
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboColorHandle);
    GL11.glColorPointer(COLOR_SIZE, GL11.GL_FLOAT, 0, 0L);

    GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
    GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);

    GL11.glDrawArrays(GL11.GL_POLYGON, 0, NUM_VERTICES);

    GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
    GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
}

Note that I'm using OpenGL in Java through LWJGL. One solution I found online is to create a color VBO at initialization for each tile, then access each one when rendering that tile. That would probably solve my problem, but it may be more expensive than I'd like considering the lookup time when there are potentially millions of hexes that are off-screen.

Is there anything else I'm doing that is glaringly wrong? Even with those solution I'm only getting ~20 fps which is obviously far lower than I'd like.


texts: How to improve the look/aspect/resolution of a Text Render in my game?

texts:
In my game there are warriors who walk the map following a path. Above their heads is shown their life (text render).

It turns out that unlike when I'm simulating the game (I'm not possessing the character) the visualization of the warriors life is practically impossible.

Image of when the warrior and my character are walking:

Even with my character stopped the visualization of life is horrible:

I have not changed much since the creation of the Text Render, but if it helps:

I want the improvement to be simply in the sense that I can easily identify the value of the warrior's life.


texts: How do games like Street Fighter compensate for bad frame rates?

texts:
I know fighting games like Street Fighter like to run and are capped to a standard 60 fps. All their combos, animations, chains, etc... are based on frames. So, how do they compensate for slowdowns when the game can't catch up the needed frame rate?

It doesn't seem an easy task like just scale the used frame count data used in the different systems of the game because of the discrete nature of frames.

Any tip on this?


texts: Worth using Box2d for collision but not physics?

texts:
I am currently doing some work in cocos2d-x and am thinking about using their box2d implementation for things like collision detection (but not necessarily response), range detection, and other things like that, which are not strictly physics based.

Is it worth doing this?  or would I be better off just writing a simple system that does checks based on location/size of my objects?


texts: Unity3D - Android pause screen - double click issue

texts:
I made a pause script for the game im developing for android.

I added the script to the GUITexture I created and placed on the top right side of the screen.The issue stands at the part where if the player clicks the pause button then clicks resume then he wants to pause the game again.When he clicks pause the second time the buttons dont show up unless he clicks again.

This is the script :

#pragma strict

var paused = false;
var isButtonVisible : boolean = true;

function OnMouseDown(){
    this.paused = !this.paused;
    Time.timeScale = 0;
    isButtonVisible = true;
}

function OnGUI(){
    if ( isButtonVisible ) {
        if(this.paused){
            if (GUI.Button(Rect(Screen.width/2-100,Screen.height/2+3,200,50),"Restart")){
                Application.LoadLevel(Application.loadedLevel);
                Time.timeScale = 1;
                isButtonVisible = false;
            }

            if (GUI.Button(Rect(Screen.width/2-100,Screen.height/2-50,200,50),"Resume")){
                Time.timeScale = 1;
                isButtonVisible = false;
            }

            // Insert the rest of the pause menu logic
            if (GUI.Button(Rect(Screen.width/2-100,Screen.height/2+56,200,50),"Main Menu")){
                Application.LoadLevel ("MainMenu");
                isButtonVisible = false;
                Time.timeScale = 1;
            }
        }
    }
}

Thank you.


texts:
Probably a silly question, but I'm having an issue where I can't view the properties of an object in the inspector window. It seems to be stuck on "Editor Settings". If I click an object I can't view its properties.

Any idea what's going on it's confused me for the past 20 minutes.


texts: How to move an object along a circumference of another object?

texts:
I am so out of math that it hurts, but for some of you this should be a piece of cake.
I want to move an object around another along its ages or circumference on a simple circular path. At the moment my game algorithm knows how to move and position a sprite just at the edge of an obstacle and now it waits for the next point to move depending on various conditions.

So the mathematical problem here is how to get (aX, aY) and (bX, bY) positions, when I know the Centre (cX, cY), the object position (oX, oY) and the distance required to move (d)


texts: How to design a drag and drop inventory system with transition from icons to game objects?

texts:
I’m trying to write a simple 2D game in Unity with an inventory where the user can drag and drop different objects on the screen.

I need the inventory to contain icons which on drag will become different game objects.

I’m struggling in positioning the game object after clicking the icon and using its drag-and-drop functionality (a script component which i attached to it).

I would really appreciate some guidelines or opinions about the design because I feel I’m doing things wrong.. What do you think?


texts: Calculate quaternion rotations between two values

texts:
I have a quaternion Q1:
X: -0.023995593190193176
Y: -0.4076451063156128
Z: 0.04357096180319786
W: 0.9117847681045532

and I have a keyframe value Q2 which is based on Q1:
X:  0.176469
Y: -0.368251
Z: 0.479782
W: 0.776569

Now my question is how can I get the correct keyframe values if there would be no extra start values ? I mean if Q1 is 1,0,0,0 (w,x,y,z). (no extra start values) So basically I need to rotate my object to the same pose but from the default values (1,0,0,0) start not from Q1.


texts:
I was implementing some quaternion rotations in too my infant 3d game engine and the rotations were really strange? Excuses my cluelessness.

Anyways this is what I have:

static XMVECTOR XMConvertToQuaternion(XMFLOAT3 axis, float radian)
{
    axis = XMNormalize3(axis);
    XMVECTOR tempAxis = XMVectorSet(axis.x, axis.y, axis.z, 1);
    XMVECTOR q = XMQuaternionRotationAxis(tempAxis, radian);
    return q;
}

Then later on down when I apply the quaternion to the world matrix I have:

XMMATRIX scaling = XMMatrixScaling(scale.x, scale.y, scale.z);
XMMATRIX rotateX = XMMatrixRotationX(radianRotation.x);
XMMATRIX rotateY = XMMatrixRotationY(radianRotation.y);
XMMATRIX rotateZ = XMMatrixRotationZ(radianRotation.z);

XMMATRIX rotateQX = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(axis, radianRotation.x));
XMMATRIX rotateQY = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(axis, radianRotation.y));
XMMATRIX rotateQZ = XMMatrixRotationQuaternion(MathHelper::XMConvertToQuaternion(axis, radianRotation.z));
XMMATRIX translate = XMMatrixTranslation(translation.x, translation.y, translation.z);
XMStoreFloat4x4(&mWorld, scaling*rotateQX*rotateQY*rotateQZ*translate);

I did get a rotation. However, the character is rotating very strangely.


texts: Online Browser Game Resource Incrementing Production Problem

texts:
I am working on a browser game where there are citys and their resource productions.
Each player has their own production rate for each resource.Lets say stone as example.
I have production rate,capacity and timestamp(when production started for that resource) for stone in  db.I am pulling production rate from db and updating production value on client(incrementing it) but not in db since updating db value each second is not a good idea.So each time user refreshes page or does some action releated to  stone,server checks timestamp and production rate and calculates what should be the value of stone in that time,i mean real value and updates client.

"stone" : {
        "capacity" : 10,
        "count" : 0,
        "timestamp" : 1531470433, // when production started.
        "rate" : 20, //stone production in a minute
}

This calculates users current stone value and updates db.

var allStoneProduction= Math.floor((currentTime - stoneDbTime) * stoneProductionRate /60)

The problem is with capacity.Players are able to increase capacity of each resource.

I can detect when stone capacity going to be full in server since i know production rate and production start time.Then i am making stonecount equal to capacity.

This code checks if storage is full.If its not it sets value of stone production.

var storageFullTime = stoneDbTime+(stoneCapacity/stoneProductionRate)*60

if(currentTime < storageFullTime || currentTime == storageFullTime){
console.log("storage is full!")

Resources.update({ownerId:userid},{$set:{"stone.count":stoneCapacity}})

}else{
Resources.update({ownerId:userid},{$set:{"stone.count":allStoneProduction}})
}

As you see allStoneProduction is actually always going up without checking capacity since its only based on rate and start timestamp.This is ok if there is no max capacity.

If stone count reaches its capacity i stop incrementing on client side by checking stonecount,stonecapacity.(10/10) lets say.

If i change capacity from 10 to 20 on db,client gets new capacity value and starts to increment it 11,12,13... until capacity 20.

But server cant follow up this.Should i also write timestamp of when capacity changed ? I couldnt really write the correct if else logic for this.

So how do i compute this capacity change in server side ? allStoneProduction value doesnt care about reaching max capacity and increasing capacity.So if change capacity and refresh page,i get a wrong stone count.(since in server logic production never stops)


texts: vector.size() instead of literal type breaking my draw code

texts:
I'm writing a simple class to draw all the debugging lines I have in my scene at once.

The code in the draw loop is this so far: (If I put for example, 2 instead of temporary2DVerts.size() where I have marked with //THIS LINE, the code works fine.) when I run the code below the line breaks //HERE. Access violation reading location 0x00000000. seems like the create buffer line is not working, but why? what's the solution?

D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * temporary2DVerts.size();// THIS LINE
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &pBuffer);

void* pVoid;

pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid); //HERE
memcpy(pVoid, &temporary2DVerts[0], sizeof(temporary2DVerts[0]) * temporary2DVerts.size());
pBuffer->Unmap();

    device->IASetInputLayout(screenVertexLayout);

    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST);

    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);

    screenPass->Apply(0);

    device->Draw(temporary2DVerts.size(), 0);

    temporary2DVerts.clear();


texts:
I'm in the process of debugging GLSL vertex shaders and I can't shake the feeling that I'm doing it wrong.

In general I have two strategies to make up for the lack of tracing

I stuff values into a debug color varying that I pass to the fragment shader and then try to interpret the colors.
I change the vertex shader code and see what happens.

I'm thinking that ideally I could make up for the lack of tracing by writing values to a texture somehow, reading the texture from the GPU and printed the values stuffed in the texture.

My guess is that there might be way better ways. Any suggestions?


texts:
I'm trying to throw the carried object in the direction of the first person controller, but unable to make it. I could make the carried object drop, but the same time i need to instantiate velocity to the carried object, so that i could forward. I'm building up a bowling game and trying to make the ball behave like the same when the player throws the ball. It should hit the alley and move forward to hit the pins. Below is what so far I've tried.

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

public class pickupobject : MonoBehaviour {
    GameObject mainCamera;
    //public GameObject empty;
    bool carrying;
   public GameObject carriedObject;
   // Camera cam;
    public float distances;
    public float smooth;
    float speed = 1000f;

    // Use this for initialization
    void Start()
    {
        //cam = GameObject.Find("MainCamera").GetComponent<Camera>();
        mainCamera = GameObject.FindWithTag("MainCamera");
    }

    // Update is called once per frame
    void Update () {
        if (carrying)
        {
            carry(carriedObject);
            CheckDrop();
        }
        else
        {
            pickup();
        }

    }

    private void pickup()
    {
        if(Input.GetKeyDown(KeyCode.E))
        {
            int x = Screen.width / 2;
            int y = Screen.height / 2;
            Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
            RaycastHit hit;
            if(Physics.Raycast(ray, out hit))
            {
                pickupable p = hit.collider.GetComponent<pickupable>();
                if(p!=null)
                {
                    carrying = true;
                    carriedObject = p.gameObject;
                }
            }
        }
    }

    void carry(GameObject o)
    {
        o.GetComponent<Rigidbody>().isKinematic = true;
        o.transform.position =  mainCamera.transform.position + mainCamera.transform.forward * distances;

    }

    //void ThrowBall()
    //{
    //    GameObject go = (GameObject)Instantiate(carriedObject,transform.forward, Quaternion.identity);
    //    pickupable to = go.GetComponent<pickupable>();
    //    to.Throw(carriedObject.transform.forward * speed);
    //}

    void CheckDrop()
    {
        if(Input.GetKeyDown(KeyCode.U))
        {
            Drop();
        }
    }

    void Drop()
    {
        carrying = false;
        // carriedObject = Instantiate(carriedObject, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation);
        carriedObject.GetComponent<Rigidbody>().isKinematic = false;
        gameObject.GetComponent<Rigidbody>().AddForce(carriedObject.transform.forward * 100);
       // carriedObject.GetComponent<Rigidbody>().AddForce(0,0,1f);
        //carriedObject.gameObject.GetComponent<Rigidbody>().isKinematic = false;
        carriedObject = null;

    }
}

Thanks in advance!


texts: Construct flow field cost map from polygon geometry

texts:
I'm looking into implementing flow fields for pathing large numbers of units across a map. From what I can find, flow fields are always constructed as a grid, and require building a cost map of obstacles and terrain levels.
Edit: Pathing cost will ultimately come from a variety of sources, not only the map geometry. However, map geometry was the only piece that comes from existing geometry, as opposed to being calculated on the fly. Other sources include:

Walkable areas of the map (including slopes but excluding cliffs and canyons)
Player-constructed buildings (which must be pathed around)
Range limits (remote-control units can not stray outside the range of the nearest control tower)
Enemy attack range (resource gathering units may want to try to steer clear of the attack range of enemy towers, if possible)
Player-created waypoints (influencing the route units will take to get to a particular destination, to avoid enemy defenses or perform patrolling)

Assuming I start with map geometry (not a grid), this would seem to mean that I would need some way of rasterizing my map polygons into the cost map.
But is rasterization the best way to accomplish this? I'm assuming this is a solved problem, but have been unsuccessful in finding other options.


texts: Extending a ScriptableObject to have a get property instead of a field, without losing serialized data

texts:
I have a ScriptableObject that's already used extensively in my project:
public class SFXClip : ScriptableObject
{
    public AudioClip clip;

    // other properties
}

I want to extend it to a derived version something like this:
public class SFXRandom : SFXClip
{
    [SerializeField] List<AudioClip> audioClips;

    override public AudioClip clip
    {
        get
        {
            return audioClips[Random.Range(0, audioClips.Count)];
        }
    }
}

But of course, I can't do that without making the clip field on the original object into a virtual property. If I do that, I'll lose all the AudioClip references in existing SFXClip instances in my project's Assets.
Is there a way I can implement this change without losing that data?


texts:
I'm trying to bounce a ball off of a wall based on angular movement.
The ball comes in at angle X ( lets say 30 ).
Bouncing off with the equation 360-ballangle works for the left and right walls
180-angle works for top and bottom walls.

Edit Sorry for the vagueness - heres whats going on
When a ball hits a wall on any side, the ball bounces right back on the same angle
. I'm not sure why it does this - I am trying to have the ball flip its X velocity on a horizontal collision, and flip its Y velocity on a verticle collision. Because I am using angular movement, I need to do this by modifying the ball's angle value, and I am not sure how to set it so it bounces correctly.

(wall.getDimensions returns a rectangle with the walls size and location)

public void moveBullet(Bullet b) {
    float xpos = (float) (speed * 2 * Math.sin(Math.toRadians(b.angle)));
    float ypos = (float) (speed * 2 * Math.cos(Math.toRadians(b.angle)));
    Rectangle bulletbounds = new Rectangle((int) (b.bulletx + xpos), (int) (b.bullety + ypos), 10, 10);
    for (Wall wall : walls) {
        if (bulletbounds.intersects(wall.getDimensions())) {
            if (b.bulletx + 10 > wall.getDimensions().x || b.bulletx < wall.getDimensions().x + wall.getDimensions().width) {
                b.angle = (360 - b.angle);
            }
            if (b.bullety - 10 < wall.getDimensions().y + wall.getDimensions().height || b.bullety > wall.getDimensions().y) {
                b.angle = (180 - b.angle);
            }
        }

    }
    xpos = (float) (speed * 2 * Math.sin(Math.toRadians(b.angle)));
    ypos = (float) (speed * 2 * Math.cos(Math.toRadians(b.angle)));
    b.bulletx += xpos;
    b.bullety += ypos;

}


texts: Why LineRenderer texture stretching when I set it to tiled?

texts:
I see this:

I have a Line Renderer set up like this:

This is the material:

As you can see even if the texture mode is "Tile" the line stretches after the first element of the line. What am I missing?


texts: Improving Rigidbody collision between real-time movable object and other Rigidbodies

texts:
I have a cube that has been scaled to be rectangular (controlled by a remote Raspberry Pi gyro/accelerometer/magnetometer) and am translating its orientation into Unity via calls to transform.localEulerAngles = new Vector3(...). This works wonderfully (the cube object modeled to be a Pi rotates perfectly), however now I'm running into issues with the actual physics.

GIF of successful roll

Initially the ball will land on and roll around the Pi object, however when I start to increase the speed of my movements the ball will sometimes fall through the Pi.

The cube has a Rigidbody (no gravity, is kinematic) and Box collider (not triggered), and the sphere has a Rigidbody (has gravity, not kinematic) and Sphere collider (not triggered) attached.  I've tried varying the collision detection from discrete to continuous on both objects and have noticed similar behaviors.

The intent is to turn this into a marble maze type game, and the issue that I have is similar.  If I roll the ball into the joint between a wall and the floor (both stretched cubes), rotate it down, and then rotate it up, the ball will fall through the joint.  I have the same movement code attached to the GameArea object below.  Again, same issue with various types of collision detection applied.

My assumption is that this is a quickness of movement thing, as the cubes overlap each other (there's not a space for the ball to sneak through).

For reference, in the physics colliders section of the project preferences, all relevant layers are supposed to collide with each other.  I don't mind getting into code-based collision detection, but this seemed fairly trivial for Unity to take care of so I was wondering if I was missing something obvious.


texts: Gamestate management without evil Singletons

texts:
I wanted to use a game state management system similiar to this approach: Managing Game States in C++

But from what I've heard singletons are evil and should not be used in 99.9%.

Can you tell me how I could modify the method of the above article to work without singletons?


texts: Problem creating levels using inherited classes/polymorphism

texts:
I'm trying to write my level classes by having a base class that each level class inherits from...The base class uses pure virtual functions.

My base class is only going to be used as a vector that'll have the inherited level classes pushed onto it...This is what my code looks like at the moment, I've tried various things and get the same result (segmentation fault).

//level.h
class Level
{
  protected:
    Mix_Music *music;
    SDL_Surface *background;
    SDL_Surface *background2;

    vector<Enemy> enemy;

    bool loaded;
    int time;
  public:
    Level();
    virtual ~Level();

    int bgX, bgY;
    int bg2X, bg2Y;
    int width, height;

    virtual void load();
    virtual void unload();

    virtual void update();
    virtual void draw();
};
//level.cpp
Level::Level()
{
  bgX = 0;
  bgY = 0;
  bg2X = 0;
  bg2Y = 0;
  width = 2048;
  height = 480;

  loaded = false;
  time = 0;
}
Level::~Level()
{
}
//virtual functions are empty...

I'm not sure exactly what I'm supposed to include in the inherited class structure, but this is what I have at the moment...

//level1.h
class Level1: public Level
{
  public:
    Level1();
   ~Level1();

    void load();
    void unload();

    void update();
    void draw();
};
//level1.cpp
Level1::Level1()
{
}
Level1::~Level1()
{
  enemy.clear();

  Mix_FreeMusic(music);
  SDL_FreeSurface(background);
  SDL_FreeSurface(background2);

  music = NULL;
  background = NULL;
  background2 = NULL;

  Mix_CloseAudio();
}

void Level1::load()
{
  music = Mix_LoadMUS("music/song1.xm");
  background = loadImage("image/background.png");
  background2 = loadImage("image/background2.png");

  Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 2, 4096);
  Mix_PlayMusic(music, -1);
}
void Level1::unload()
{
}
//functions have level-specific code in them...

Right now for testing purposes, I just have the main loop call Level1 level1; and use the functions, but when I run the game I get a segmentation fault.  This is the first time I've tried writing inherited classes, so I know I'm doing something wrong, but I can't seem to figure out what exactly.


texts:
I am wondering about in-game level design. My current situation revolves around Tiled - I have many different layers with different types of objects in them (for anyone who isn't familiar with Tiled, an object is nothing more than a coordinate with arbitrary properties assigned to it).

I am currently re-compiling the game every time I make a little change to my map file to see if everything is positioned properly. Is there a way for me to have my game automatically re-load the level if a map file change is detected? Does XNA even allow for this, or does the way the content pipeline work not allow for dynamic content in such a way? Any tips or suggestions are absolutely welcome.


texts: How to handle clothing poke through for customizable characters?

texts:
I am in the process of developing a character customization system and I want to setup the base character model (the body) so that it works with which ever process I end up using. There are 2 aims here:

1) Ensuring that the base mesh (body) does not poke through the clothing mesh and vice versa
2) Ensuring that a customized character is properly optimized, i.e. there are as few unseen polygons being rendered as possible

The clothing is a rigged and skinned mesh, which in T pose has no poke through at all. However unfortunately when animating, despite my best efforts, there is always some poke through happening between the clothing and base mesh. I have considered having a few different versions of the base character model (body) which is switched out based on what kind of clothing the character has equipped. Therefore only the parts of the body which will be visible (not covered by the clothing) are actually rendered. Please see the image below:

The problem with this approach is that there could potentially need to be a large number of base meshes to cover all possible clothing variations. For example, a t-shirt alone could have any number of sleeve lengths or not have sleeves at all. Combined with other clothing such as pants or skirts, these could also be any number of lengths; and the player has the option to mix and match these in any way they want eg. t-shirt with short shorts, shorts, 3/4 pants, pants etc.

So I am wondering whether this approach is a good option or whether a better alternative exists. I look forward to some advice on this.


texts:
I'm trying to build a very small example to run input logic but i'm facing a small issue. The code below is runnable with MonoGame v3.7.0.1708.

My problem is that whenever you press a key (here the example is for the D key) i'm displaying a small text on the console.

But you will see if you run the code that the display happens with lag. When i press the "D" key on my keyboard, the message is displayed only ~200ms after the input.

You can for example do a fast press on the keyboard and the message will be displayed after the release of the key.

Does anyone have any idea why it's happening? Thanks!

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;

namespace TestProject
{
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    GameInput gameInput;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        gameInput = new GameInput();
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent() {}

    protected override void UnloadContent() {}

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        base.Update(gameTime);
        gameInput.Update();
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
    }
}

public class GameInput
{
    public bool _dKeyPressed = false;

    public void Update()
    {
        KeyboardState keyState = Keyboard.GetState();
        if (keyState.IsKeyDown(Keys.D))
        {
            if (!_dKeyPressed)
            {
                Console.WriteLine("[GameInput] D key is pressed.");
            }
            _dKeyPressed = true;
        }
        else if (_dKeyPressed)
        {
            Console.WriteLine("[GameInput] D key is released.");
            _dKeyPressed = false;
        }
    }
}
}


texts: Handling game logic events by behavior components

texts:
My question continues on topic discussed here

I have tried implementing attribute/behavior design
and here is a quick example demonstrating the issue.

class HealthAttribute : public ActorAttribute
{
public:
    HealthAttribute( float val ) : mValue( val ) { }

    float Get( void ) const { return mValue; }
    void Set( float val ) { mValue = val; }

private:
    float mValue;

};

class HealthBehavior : public ActorBehavior
{
public:
    HealthBehavior( shared_ptr< HealthAttribute > health )
        : pHealth( health )
    {
        // Set OnDamage() to listen for game logic event "DamageEvent"
    }

    void OnDamage( IEventDataPtr pEventData )
    {
        // Check DamageEvent target entity
        // ( compare my entity ID with event's target entity ID )

        // If not my entity, do nothing
        // Else, modify health attribute with received DamageEvent data
    }

protected:
    shared_ptr< HealthAttribute > pHealth;

};

My question - is it possible to get rid of this annoying check for game logic events?
In the current implementation when some entity must receive damage, game logic just fires off event that contains damage value and the entity id which should receive that damage.
And all HealthBehaviors are subscribed to the DamageEvent type, which leads to any entity possesing HealthBehavior call OnDamage() even if he is not the addressee.


texts: I'm sending UDP packet to android over a wireless network from some other software . how can I receive that in android ? should I write a client in android to get the data?


texts: LibGDX Box2d - How to only setLinearVelocity on X axis - problem while jumping

texts:
public void update(float dt){
    float currentYVelocity = body.getLinearVelocity().y;

    switch(currentMoveState){
        case moveLEFT: body.setLinearVelocity(-walkSpeed * ppm, currentYVelocity);
            break;
        case moveRIGHT: body.setLinearVelocity(walkSpeed * ppm, currentYVelocity);
            break;
        case moveSTANDING: body.setLinearVelocity(0,currentYVelocity);
    }

    //handle input...
    if (Gdx.input.isKeyPressed(Input.Keys.A) && body.getLinearVelocity().x >= -2
            && body.getPosition().x >= 0.08f){
        currentMoveState = moveState.moveLEFT;
        //body.applyLinearImpulse(new Vector2(-walkSpeed * ppm,0), body.getWorldCenter(), true);
    }
    else if (Gdx.input.isKeyPressed(Input.Keys.D) && body.getLinearVelocity().x <= 2 ){
        currentMoveState = moveState.moveRIGHT;
        //body.applyLinearImpulse(new Vector2(walkSpeed * ppm, 0), body.getWorldCenter(), true);
    }
    else
        currentMoveState = moveState.moveSTANDING;
    if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
        body.applyLinearImpulse(new Vector2(0, jumpSpeed * ppm), body.getWorldCenter(), true);
    }

    // sets the players texture sprite to be same position as the box2d circle body...
    this.setBounds(body.getPosition().x - 8, body.getPosition().y - 8, 16, 16);
}

I have the above code in place. I'm using LibGDX and Box2d. Im trying to make a single screen platformer similar to old-style Donkey Kong.

My issue is that when I move and jump at the same time, the Y velocity is being heavily affected. When jumping without moving left/right it is fine, but if you hold left whilst jumping the character stays almost suspended in mid air and you can acheive all kinds of irregularities with trying to jump and move.

I tried adding the variable 'currentYvelocity' and passing that into the Y value each time i alter 'setLinearVelocity(x,y)' but I can see that this is the issue because somehow it must be removing the new calulation from Y velocity and replacing it with the previous frame perhaps..?!?

I've wracked my brains and now everything I try makes it worse.

Can anyone tell me of a proper solution to this please? (Or perhaps I'm almost right and just need a helping hint :) )

Anyways, thanks in advance for any help!

EDIT: By the way, I have now changed the currentYVelocity by removing that variable and just calling getLineaarVelocity.y in all the movement methods. But this had no effect unfortunately on my jumping whilst walking problem.


texts: Calculate the aircraft's movement path in which its side speed is required

texts:
I am working on an implementation problem in which given an aircraft and the objective of the system is to find the quickest route (optimal in terms of time) from point A (contains the information of the aircraft's 2D position and heading which is looked from top view) to point B (contains the same information as point A). There are several conditions:

The aircraft must use the full speed. By full speed, I mean the engine must use its maximum speed as much as it can provide in the current condition (e.g., if some of the engines are destroyed, the maximum speed decreases). There are three types of the speed:

Forward speed
Side speed
Turning speed

The aircraft doesn't have to use all three types of the speed simultaneously.

The answer of the following post here has answered some of my problems, but there still some of the issues I want to solve, which is if I want to include the side speed of the aircraft to the movement, how will the calculation of the movement path (especially when the aircraft turns) look like?
Please kindly recommend and I would appreciate any ideas for this problem.


texts: How to create a skybox in an infinite world like minecraft?

texts:
I'm making a minecraft-clone game in C++ using OpenGL.

I created a skybox using OpenGL's cube map but the camera can go outside of the skybox since it's an infinite world. Then I changed it to update the skybox's coordinate based on camera's coordinate like below but it didn't change anything.

How can I make a skybox stay at a relative position from the camera?

auto coord = camera.getCoords();
// positive x
skyboxMesh->addFace(
              coord.x + size, coord.y + size, coord.z - size,
              coord.x + size, coord.y + size, coord.z + size,
              coord.x + size, coord.y - size, coord.z - size,
              coord.x + size, coord.y - size, coord.z + size
              );


texts: What is the point in using API such as Open GL or DirectX when there are game engines?

texts: I was wondering why  today programmers place so much emphasis on API like DirectX, and even OpenGl. As far as I know, you'd need thousands of lines of code to make a simple 3D game using one of the aforementioned. But with game engines like Unity, the process is simplified and you can pretty much drag around shapes to create the graphics in lieu of programming it. So what I wanted to know: why is knowing APIs DirectX more preferable than being knowledgeable in Unity, other than the fact that with an API you can code it to be portable on other systems. To me it's like choosing Assembly over a high level language like C. Sure, with assembly I'll really understand what's happening at machine level, but it's take a lot longer to write programs using it and it would be a lot harder to debug.


texts: Slick2D - Cannot instantiate the type Image

texts:
I am getting this strange error and I cannot for the life of me figure out why:

    Cannot instantiate the type Image

CODE:

import java.awt.Image;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class MainMenuState extends BasicGameState {

    int stateID = -1;

    Image background = null;
    Image startGameOption = null;
    Image exitOption = null;

    float startGameScale = 1;
    float exitScale = 1;
    MainMenuState( int stateID )
    {
       this.stateID = stateID;
    }

    public int getID() {
        return stateID;
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        try {

        background = new Image("data/menu.jpg");

        Image menuOptions = new Image("data/menuoptions.png");

        startGameOption = menuOptions.getSubImage(0, 0, 377, 71);

        exitOption = menuOptions.getSubImage(0, 71, 377, 71);

        }catch (SlickException e) {
            System.err.print(e);
        }
    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {

    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {

    }

}

Why do I get this error? I've googled endlessly and nobody else has it, this worked fine in my other game. Any ideas?


texts:
I am trying a box2d body to rotate following the mouse. Here's an image to clarify what I mean.

The red and blue circles are current point of the mouse and the body (of corresponding color) moving/rotating to follow it. Basically the rectangle should rotate with its one end pointed towards where the mouse pointer is.

Here's my code so far,

 World world;
    Body body, bullet;
    Box2DDebugRenderer debugRenderer;
    OrthographicCamera camera;

    @Override
    public void create() {

        world = new World(new Vector2(0, 0f), true);
        debugRenderer = new Box2DDebugRenderer();
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set(10, 10);
        body = world.createBody(bodyDef);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(2, 5);
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 1f;
        Fixture fixture = body.createFixture(fixtureDef);

        shape.dispose();

        Gdx.input.setInputProcessor(this);

        camera = new OrthographicCamera(200, 100 * (h / w));
        camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);
        camera.update();

    }
 @Override
    public void render() {

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);
        camera.update();
        debugRenderer.render(world, camera.combined);
    }

  @Override
    public boolean mouseMoved(int screenX, int screenY) {
        int mouseX = screenX;
        int mouseY = Gdx.graphics.getHeight() - screenY;
        float rotateAngle = MathUtils.radiansToDegrees * MathUtils.atan2((float) mouseY - (float) body.getPosition().y, (float) mouseX - (float) body.getPosition().x);
        body.setTransform(body.getPosition(), rotateAngle / 57.2957795f);
        return true;
    }

And here's a gif of how it appears now.

as you can see the body gets skewed and also doesn't rotate properly. What am I missing?


texts: Unity 2019 depth-only camera now overwrites everything

texts:
We have a pretty traditional camera stacking set up: UI camera on top of a everything-else camera.

The UI camera is set to only clear depth, and only draws the UI layer.  The everything-else camera is set to clear via skybox and all layers but UI.  Only the everything-else camera contains a post-processing layer component; disabling it does seem to make everything work the way it used to.

The UI camera has a higher depth than the everything-else camera, in case someone suggests otherwise.

In 2018 this exact arrangement worked as intended.  In 2019, the UI camera's view is the only thing visible.

I've found several forum posts on Unity by Unity Technologies about the light-weight pipeline breaking this functionality, but we're not using any of the new pipelines.  We simply upgraded, and I can't find any indication that we are using the new pipelines.  Supposedly everything works normally as long as you don't use the new pipelines, but this is proving false so far.

Since this camera arrangement is very common, I can't imagine I am alone!


texts: Why here does my use of GetOwner() make UE4 crash editor?

texts:
I am new to Unreal Engine. I am following a tutorial where at the end he challenged me to build some extra features to the game.

Basically. This code crashes UE4, but I found out if I remove "GetOwner()->" from the code it works just fine.

But I struggle to understand why this is. I understand that maybe the 'Switch' variable is already at Root level (ie. is the Owner already) but surely the GetOwner() function could just return itself in that scenario?

Here is my function (The line causing crash is 4th line of actual code below. If I make it "    UBoxComponent* SwitchCollider = Switch->FindComponentByClass();" instead, the game works perfectly:

float UDoorOpener::GetCurrentWeightOnPlate()
{
float TotalMass = 0;

// Find all the overlapping actors
TArray<AActor*> OverlappingActors;
UBoxComponent* SwitchCollider = Switch->GetOwner()->FindComponentByClass<UBoxComponent>();
if (SwitchCollider)
{
    SwitchCollider->GetOverlappingActors(OUT OverlappingActors);

    if (OverlappingActors.Num() > 0)
    {
        UE_LOG(LogTemp, Warning, TEXT("MOFOOOOO"));

        // Iterate through them and add mass to total
        for (AActor* Element : OverlappingActors)
        {
            float ObjectMass = Element->FindComponentByClass<UPrimitiveComponent>()->GetMass();
            TotalMass += ObjectMass;
            UE_LOG(LogTemp, Warning, TEXT("%s has mass of %f. Total Mass currently: %f"), *Element->GetName(), ObjectMass, TotalMass);

        }
    }
}
else
{
    UE_LOG(LogTemp, Error, TEXT("SwitchCollider is null!"));
}

return TotalMass;

}


texts: Persisting unlocked characters in Player Prefs

texts:
I am  working on a character selection menu in Unity.

If you have enough coins, you can buy your desired character. Once player buys one, that character must not be locked on game restart, the number of coins must not be changed again, and the lock image (a GameObject I defined under name "wood" and acts as a lock) must disappear.

Everything works fine when I buy one character, but when I buy another one, the previous one returns to locked mode, but its image (wood) has already disappeared (I mean, I should have enough coins to re-buy an already bought character).

I guess there must be something wrong with this code isPlanesold = PlayerPrefs.GetInt("isPlanesold"); because it changes as a character is bought.

Here is my script:

int isPlanesold;
public static int chnum; //character number that must be referenced on another scene
public Button WhitePlane;
public Button YellowPlane;
public GameObject wood1;
public GameObject wood2;

void Start () {

        PlayerPrefs.SetString ("BluePlane", "on");
        if (PlayerPrefs.GetString ("WhitePlane") == "on") {
            wood1.SetActive (false);
        }
        if (PlayerPrefs.GetString ("YellowPlane") == "on") {
            wood2.SetActive (false);
        }

                UIManager2.coin_score = PlayerPrefs.GetInt ("Score");
        isPlanesold = PlayerPrefs.GetInt ("isPlanesold");

}

            public void BuyWhitePlane () {

        if (isPlanesold == 1) {
            PlayerPrefs.SetInt ("isPlanesold", 1);
            chnum = 2;
            PlayerPrefs.Save ();
            SceneManager.LoadScene ("Menu2");
        } else if (UIManager2.coin_score >= 1) {
            PlayerPrefs.SetInt ("isPlanesold", 1);
            chnum = 2;
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score--);
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score);
            PlayerPrefs.Save ();
            PlayerPrefs.SetString ("WhitePlane", "on");
            SceneManager.LoadScene ("Menu2");

            }
        else
        {
            Debug.Log ("You Don't Have The Score");

        }

    }

    public void BuyYellowPlane () {

        if (isPlanesold == 2) {
            PlayerPrefs.SetInt ("isPlanesold", 2);
            chnum = 3;
            PlayerPrefs.Save ();
            SceneManager.LoadScene ("Menu2");
        } else if (UIManager2.coin_score >= 2) {
            PlayerPrefs.SetInt ("isPlanesold", 2);
            chnum = 3;
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score -= 2);
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score);
            PlayerPrefs.Save ();
            PlayerPrefs.SetString ("YellowPlane", "on");
            SceneManager.LoadScene ("Menu2");

        }
        else
        {
            Debug.Log ("You Don't Have The Score");

        }

    }

PlayerPrefs.SetString ("BluePlane", "on"); refers to a character that's unlocked by default.


texts: Unity | How to create C# classes with different properties like Objects in javascript and put them in an array?

texts:
I just started my gamedev journey on unity this week and while I have a background with coding, I'm still somewhat of a beginner. Last year I made a text/UI based game on the web browser with javascript and have been trying to make the same game on Unity.

One of the main features of my game is that you press a button to "go hunting" and I had an array filled with enemies that were objects with different properties such as health, mana, attack, etc...

Then I'd randomly pick one of those objects from the array to be chosen as my enemy that I'd fight. I've been trying to figure out the best way to do this with C# and I might just be overthinking this.

As a bonus, I'd also like to be able to see the individual enemy objects in the array in my inspector if possible so I could tweak the stats within unity.

I've looked at scriptableObjects and different things but I am having a hard time putting it all together in an array from within unity.

[System.Serializable]
public class playerClass
{
    public string playerName;
    public int lvl;
    public int maxHealth;
    public int health;
    public int maxEnergy;
    public int energy;
    public int exp;
}

public class playerScript : MonoBehaviour
{
    public playerClass player;

}

This is how I created an object for the player, I want to do something similar for the enemies but put them in an array so I could randomly pick from them.

If there is a better way to do this I'd also welcome some advice :) thank you


texts: What features should a 2D graphics library have?

texts:
I am making a 2D graphics library in Python designed to make 2D easy and fast. Internally it uses OpenGL. The library does cover a bit more then a graphics library, it also includes windowing and sound (and all necessary features to get working, like texture loading).

I've got a good beginning working with good performance, and I'd like to expand and refine my feature set.

Now I'm wondering, what features should a 2D graphics library have? After some brainstorming I made a little list:

Fast sprite class for displaying rotated, scaled, colored and translated textures
Sprite batching
Drawing geometry: lines, polygons, circles, etc
Alpha with blending modes on all of the above
Easy texture loading (from file and memory)
Texture regions (and texture atlases)
Blitting texture(regions) into other textures
Particle systems
Off-screen rendering surfaces (FBO's?)

But I feel I have only scratched the surface of features. What am I missing?

One thing you must keep in mind that all of this in Python with C extensions. Any work in the library is fast, any work the user must do is relatively much slower. In addition to that Python calls are quite expensive, so the library largely benefits from batching.

(In case anyone cares, the library in question is pygrafix and can be found here: http://github.com/nightcracker/pygrafix)


texts:
My goal is to get a RGB value of a pixel based of off a X,Y coordinate.

I have been working on AIs for a small project attempting to make a bot that can pass through a maze. I want to get the pixel color in front of the bot to test if it is a wall or not. I have no example code because i don't know exactly where to start.


texts: Have a while loops but inputs depend on events fired, what are some ways on getting the input?

texts:
I think I'm at a conundrum here, I've creating a matching game in C# winforms. And I'm 90% done, the only thing left is the game loop.

The matching games consits of two multidimensional arrrays which are panels. And after I set everything up, I can RunGame(), which where my game loop is, the problem I am having is getting input. I'm not sure how to do that yet.

For example.

It's a while loop.

So,

while(game.isRunning()){

//get input from player.

//getchoice then redraw panels accordingly

//get input from player 2.

//getchoice then redraw panels accordingly

}

The problem is my players click on panels that's how I get the choice they've made. So I wanted to know if you guys have any good ways of getting input in a loop from an event that will be launched outside the loop for a game.

Thanks.


texts: I am curious as to what technique(s) are used to load files in while a game is running. For example, Minecraft will load chunks as you get within a certain range of them. How is this achieved without producing lag? Is multithreading involved?


texts: Efficient algorithm for simultaneously updating game objects which need to be updated

texts:
I have a grid of objects like this:

 1
      +
 F

1 is equal to the constant 1, F flickers between 0 and 1 each tick,
and + is equal to the sum of the 1 and the F.

I want to update these values as described above. The 1 won't change, the F will change from 0 to 1 and vice-versa, and the + will change to the sum.

I could just do a loop:

for node in nodes {
    if(node.type == '+') {
        node.value = node.input1.value + node.input2.value;
    }
    if(node.type == '1') { ... }
    if(node.type == 'F') { ... }
}

but the problem is that this will depend on the order of iteration. If the F
is iterated on first, then it will be set to 1 from an initial value of 0, then the + would equal 1 + 1, i.e. 2. But if the + was first, the result would be 1 + 0 = 0 and the NEXT tick would be 1 + 1 = 2.

I want to do this simultaneously. So I thought I could have a map of new values:

global map = new HashMap<Node, double>();
...
map.clear();
for node in nodes {
    if(node.type == '1') {}
    if(node.type == 'F') {
        map.set(node, node.value == 1 ? 0 : 1);
    }
    if(node.type == '+') {
        map.set(node, node.input1.value + node.input2.value);
    }
}
map.forEach(k, v -> k.value = v);

but this is probably inefficient as all values have to be looped over and entries in the map must be created for each node (node count is expected to be alot, around 10,000).

How do I do this? I probably need a list of "update required" nodes but I'm not sure what to do exactly, especially to do it simultaneously.

Examples:

1
 \
  == + === + === + == (flickers between 6 and 7 starting at 6 due to F flickering)
 /        /     /
F        3     2

// Nodes can be created by the player

1 => + <= 2
     |
     |
     (equals 3)

// Player creates a node:

1 => + <= 2
     |
     |
     (factorial) ===> (equals 6)

There can be multiple of these connected nodes at a time:

1 => + <= 2
     |
     |
     (equals 3)

2 => + <= 3
     |
     |
     (equals 5)

// If the player chooses, they can connect these 2 together:

1 => + <= 2
     |
     |
     -===========
                |
2 => + <= 3     |
     |          + =====> (equals 8)
     |          |
     -===========

Nodes can be inputs to themselves, or have no inputs (in which case the inputs default to 0):

     =====> (starts at 1 in the first tick, then keeps incrementing.)
     |
1 => + <==
     |   |
     =====


texts: Best base resolution for a pixelart project for bigger audience

texts:
I've been working on Top-down 2D pixel art project for quite some time. When I first started my project, I actually set application surface, display and game window to match 1:1 - with that said, the game performed well and project looked pixel-perfect without tearing or anything... BUT, I'm not making Age of Empires or Sim City clone, where as bigger display you got, as more you see, but as smaller things get. So, I rewrote my resolution script completely to a fixed size...

Now, the thing is:

Images/sprites are mostly between 32x32 and 64x64
I need to figure out a good base resolution for bigger audience (like
Steam, community etc.)

The game can't have infinitely large view, because character shouldn't see too far and at the same time be barely visible on large monitors
With that said, it has to look +/- ok on different display
resolutions, but attain best quality using aspect ratio function, even if that means black borders around the view
Game has a configuration page for different resolutions, but that
will affect only how much the stuff has to stretch etc. and is not currently used from user interface (testing from in-game console only)

The question basically is:

Best - 640x480 VS 800x600?
What base resolution "Hotline Miami" videogame might be considered to
have?
Does the whole resolution concept really matter and I should worry
about user experience with this?

This whole thing a bit reminds me of Fallout 2 with locked "2x scaling on" on high-res, which basically did similarly to what I'm going forward to...

For a better understanding of what I'm trying to say, here's a visual aspect of this (Green line is basically the border of the room, but due to the display resolution, you can see past the border):

BEFORE

AFTER

** The "after" image doesn't use aspect ratio in this picture, but instead shows past the actual supposed viewing frame, this is why you don't see black boxes on sides... this was later on fixed though


texts:
I'm trying to handle slopes in a tiles based world. I'm using basic linear interpolation to find the Y coordinate of the character based on his X position. But i have a problem, when the character move up or down the slopes the sprite is all jittery, it doesn't move smoothly and i can't figure out why.

I don't use a "true physics engine" all the engine does is AABB collision and tell when a collision occurs and let you handle the reaction. When the character is on a slope no "gravity" (Y velocity) is applied the Y position is adjusted by hand using the linear interpolation result.

Here is the linear interpolation function that i use :

float InterpolateY(Vector2 point1, Vector2 point2, float x)
{
    float x1 = point1.X;
    float y1 = point1.Y;

    float x2 = point2.X;
    float y2 = point2.Y;

    float y = y1 + (x - x1) * (y2 - y1) / (x2 - x1);

    return y;
}

I've made a webm to show you the problem (ignore the fact that the sprite sink into other tile it doesn't matter for the moment)

Link to the webm : https://webmshare.com/play/vPXLD


texts: What is the "TangentsW" attribute inside the FBX file format for?

texts: sometimes it is -1, sometimes is +1. Do I need it for the rendering of the normal maps?


texts: Doesn't multiple inheritance solve all problems that entity systems do?

texts:
The question is pretty self explaining: doesn't multiple inheritance solve all the problems that entity systems also solve?

I just remembered a term called "multiple inheritance", and that seems to solve a lot of bloating problems that classical inheritance imposed.


texts: Is it possible to have a script built-in into a custom resource?

texts:
Here's a rudimentary custom resource:

extends Resource

export(Resource) var scr

I can drag a pre-made .gd script into this exported property in Inspector, and it works as intended. I can click on the exported property field and embed a resource (like "New ShaderMaterial"), and it would also work as intended, and I would be able to edit that sub-resource normally. However, if I click on the exported property and select "New GDScript", there doesn't seem to be a way to open the new gdscript for editing. Is it possible to embed a gdscript sub-resource the same way you can embed a different sub-resource?


texts: 3D prospective with geometry shader objects

texts:
I am wanting to be able to render objects with a geometry shader and allow them to rotate with the camera perspective...this is what I have so far, as a example

Vertex shader

#version 400 core

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main()
{
    vec4 worldPosition = transformationMatrix * vec4(0,0,0, 1.0);
    vec4 positionRelitiveToCam = viewMatrix * worldPosition;
    gl_Position = projectionMatrix * positionRelitiveToCam;
}

Geometry Shader

#version 400 core
layout(points) in;
layout(triangle_strip, max_vertices = 3) out;

void main() {
    gl_Position = gl_in[0].gl_Position + vec4(-1.0, 0.0, 0.0, 0.0);
    EmitVertex();

    gl_Position = gl_in[0].gl_Position + vec4(1.0, 0.0, 0.0, 0.0);
    EmitVertex();

    gl_Position = gl_in[0].gl_Position + vec4(0.0, 2.0, 0.0, 0.0);
    EmitVertex();

    EndPrimitive();
}

As you can see, I am able  to draw a triangle with POV working but as I rotate around it, the triangle does not rotate. Ideas?


texts: GPU usage below 90% = poorly optimized game

texts:
Ok so not exactly a "development" question but highly related.

When I play games I often look at performance numbers, like CPU usage, GPU usage, memory usage and others. Let us talk about GPU usage on PC. Here is my observation: there are two kinds of games:

MAX GPU usage: these games produce either 60 FPS or 90%+ GPU usage.
POOR GPU usage: these games produce less than 60 FPS and less than 90% GPU usage at the same time

MAX GPU examples (trying to make sure my idea is understood ok):

50 FPS, 100% GPU
60 FPS, 90% GPU
60 FPS, 50% GPU (also legit)

POOR GPU examples:

30 FPS, 60% GPU (FPS limit is 60)
40 FPS, 50% GPU

It appears that MAX GPU games use GPU efficiently to provide best performance while POOR GPU games are bottlenecked for some reason. U get few FPS, low GPU load and none of CPU cores reach 100% load. I checked and re-checked my PC many times and I don't see any specific issue which could make some games perform poorly, besides other games reach 90%+ GPU usage with no problem. Also I am not the only person who observed such behaviour.

So the question is: POOR GPU games are poorly optimized, either on purpose or because of lack of effort. True or false?

Also, it appears that MAX GPU games are probably multithreaded? I suspect that poor-gpu games go like this: use main thread

loop
  update;
  draw;

while max-gpu games go like this: use two threads

loop
  start-update in another thread;
  start-draw;
  wait & synchronize

It is of course more complex than that but the general idea is basically that max-gpu games render stuff and update stuff at the same time; that is how higher GPU usage is achieved.

Ideas? Thoughts? Thanks


texts: Isometric map (2D) - Click detection - Mouse mapping - How to implement it?

texts:
I'm building an isometric engine.

I use TILE_SIZE * TILE_SIZE (minecraft like) tiles.
(I'm using 64 * 64 tiles but I can change the number when I want)

I can access for each tiles to this informations :

 - OFFSET_LEFT(same for every tile on a layer)
 - OFFSET_TOP(same for every tile on a layer)

 - x (classic 2D tiled coordinates)
 - y(//)

 - isometric i

 - isometric j

Tile are drawed at (i * TILE_SIZE, j * TILE_SIZE)
I use the following formula to get from x to i and y to j :

int i = (x - y) / 2,
    j = (x + y) / 4;

No problem for displaying, I got my diamond shape :

I try to find a formula to convert my cursor coordinates into those isometrics ones(i, j) with the following questions in mind I wrote on the screenshot.

After doing i * TILE_SIZE, etc... Finding a way to handle offsets(??????)...

I'm gonna render this off-screen :

And banzai, tile detection with some getPixel()...

But to do that, I have to resolve the problems I highlighted with the balise  in the following topic.

Final purpose : get the tile index in my tile array(wich I suppose I can have with i + j ?)

I'm without a clue for days, reading a lot of topic, but some of them sprout some chinese like sqrt(what the... is this creature ?) or matrix transform ????

So even with all the topic on the subject here, I was unable to find a proper solution fulfilling my project's need. Thanks for reading me; ask me if I missed some informations.

EDIT :
About the link you gave :

int i = y / tile_size + x / (2 * tile_size),
j = y / tile_size - x / (4 * tile_size);

This one give some 'good results'(I don't really know if it's working but the numbers seem rights) but I can't handle :

- offsets
- when I click outside the map


texts:
We are working on a tablet game in Unity Pro (for the first time). Unity's profiler works great for probing the CPU, but the tablet's GPU isn't supported in the profiler, so we have no idea where the rendering bottlenecks are.

Are there any other means of profiling the GPU of an android tablet? (We are working with a Samsung galaxy tab 2 10.1 ) How do other mobile devs do this?

We are basically looking for any ways of getting info from the gpu as we're running the game. Benchmarking software wouldn't help; we don't need benchmark scores.

Cheers!


texts: Why do modern games use a render-to-texture approach for mirrors?

texts:
When looking at old games like Mario64 or DukeNukem3D, all the mirrors in the game are essentially just holes in the wall with a mirrored copy of the geometry in front of the mirror put behind them. In the case of DukeNukem3D one can even activate no-clip and walk into that mirrored room.

In contrast modern games use a render-to-texture approach for mirrors. This leads to the mirrors getting noticeably pixelated when getting to close to them. One of the first games I noticed this approach was Luigi's Mansion, but it seems to be used in almost all modern games.

What change in the hardware or engines made the second approach become so dominant these days and what are the benefits to it? In terms of pure visuals the first approach seems superior, as it doesn't suffer from pixelation issues.


texts: Why is clicking too fast giving me a missingReferenceException in Unity?

texts:
I made a small method that will quickly give the player a "flashlike" display when a sheep is killed. However clicking too fast will trigger a missingReferenceException. Because it registers the raycast a second time. Is this due to the delay on the DestroyObject() or something else?

private IEnumerator startFlashing(GameObject sheep)
{
    sheep.gameObject.GetComponent<Rigidbody>().freezeRotation = true;
    sheep.gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
    sheep.SetActive(false);
    yield return new WaitForSeconds(theTimeBetweenFlashes);
    sheep.SetActive(true);
    DestroyObject(sheep.gameObject, 0.1f);
}


texts:
Does anyone know of any good (and preferably free) Sprite Animation Toolkits/Libraries for iOS development?

This library should be able to handle the collision detection and the movement of the sprites.  Back in the 90's there was a Pascal library called Sprite Animation Toolkit by Ingemar Ragnemalm that handled a lot of the heft to create animations and the such.  I am just wondering if there is anything like that in the iOS world?


texts: How to implement throw curve with virtual height in a 2D side-view game

texts:
I am working on a 2d side-view soccer game that looks like this image:

But now I stuck on how to implement parabola pass ball. I have found many questions corresponding to my problem:

Calculating velocity needed to hit target in parabolic arc
Throw object towards predefined place?
http://en.wikipedia.org/wiki/Trajectory_of_a_projectile

But they all just tell how to draw parabola in simple 2d space. In my game, except for the normal x,y there is also a virtual height coordinate, so the final viewing position of the ball is:

world position + current_height * Calc_Scale. (Calc_Scale is 0.3f)

Currently I did it the following way: I calculate the pass time(T) and distance(D) from point A to B

the pct = current_time / T
current_height = D * (4* pct - 4 * pct* pct)

Unfortunately, it looks bad...

UPDATE: @ashes999  I tried quadratic equation like current_height = D * (4* pct - 4 * pct* pct), it is not good(I am continuing to try different factors).I am pretty sure sin/cos can not work here, for example, player A is in(300, 200), B is(300, 800), the ball will make a direct line beyond B's head then drop to B's feet(or head), and this can not be done by cos/sin way, And I am thinking can this be done by some sort of projection, I just calculate the x,y,z then project z value into y axis?

void RSSoccerBall::Pass(const vector2d& target, double force)
{
vector2d DistVec(target - m_vPosition);
m_PassDistance = DistVec.getLength();
if(m_PassDistance > MaxShortPassDistance)
{
m_CurrentPassTime = 0.f;
m_PassTime = TimeToCoverDistance(target, m_vPosition, force, true);
}
}

void RSSoccerBall::update(float dt)
{
//for parabola calc
if(m_CurrentPassTime < m_PassTime)
{
m_CurrentPassTime += dt;
float pct = m_CurrentPassTime / m_PassTime;

m_Height = m_PassDistance * 0.7 *  (4 * pct - 4 * pct * pct);
}
vector2d    exactViewPos = m_vPosition; //m_vPosition is the 2d world position
exactViewPos.y += m_Height;
//render football at exactViewPos;
...
}

@Mario, These are my code ,I have used an extra variable to store height. - Determing an object's position along a curve over time this is where the equation from

I do not want the top of the arc always to be at 50% distance traveled, because player A and B probably not in same Y value, if B's Y value is higher than A's Y, the top of the arc will be exceed 50%.
I found a wiki link: - http://en.wikipedia.org/wiki/Range_of_a_projectile
describe Ideal projectile motion on uneven ground, but the formulas are complicated for me to convert into current situation(we have start point, end point, start velocity, travel time)

Can anyone give me some pointers how to accomplish that?


texts: What input and window handler should I learn for complement OpenGL?

texts:
I have a good base in C++ programming and I did some 2D games using SDL. Now I want to start making 3D games, but as much as posible, I want to learn following the standars of the profesional industry.
I think learning openGL I will have more acuratte skills for programming 3D graphics, so I prefer to study openGL instead of a game engine. But my cuestion is, what library I should choice for complement openGL in the area of the input and windows handler, if posible, following the standars of the industry?

Thanks you in advance for the help! (And sorry for my bad english)


texts:
Let's say you have a bunch of tweens running like this:

http://holbrook.no/tests/featherfall.html

Now you want to scroll them horizontally while they fall. By updating camera x, they start moving, but in the end, the camera x value will overflow. And besides, one might want to wrap some background graphics before then.

Therefore we need to periodically snap the camera back to the original position. But then the tweens will snap back too.

So the individual sprites need a transform value on top of the current tween position to correct for the camera repositioning.

I haven't found any setting in Phaser for this. Any ideas?

EDIT:

It's possible to work around it with keeping a global variable to keep track of the camera yanking, and adding it manually to the onUpdateCallback of the tween, and consolidating the difference with the next tween change. But the hack seems to be glitching sometimes, and I suspect it's slower than if an internal transform variable could be used. Anyway, here's the result:

http://holbrook.no/tests/featherfallscrolled.html


texts: Unity 3D Imported Assets Rotated Backwards in-game

texts:
I'm putting together boilerplate for a Unity FPS game, and having an issue with importing an Asset Store model.
All of my weapons are asset store prefabs. I'm new to Unity, but this makes me think there's something about the imported prefabs themselves that's setting the axis alignment of the models in-game.
Anyone know what I'm missing to fix this and rotate that model in the world (without just writing a model script to rotate it programmatically every time) ?


texts: most compact way to represent dice face translations rolling in cardinal directions

texts:
I'm making a 2-D dice rolling game in BASIC (think mechanics similar to Devil Dice on the Playstation, but top-down 2D graphics). I'm trying to accurately represent the transitions of a die when rolling it from one face to another along the cardinal directions. I can look up the current value of a die at a given position but I'm not maintaining actual object representations corresponding to a physical die, so modeling the 3D dice in game is out.

I can think of two ways to do this, but can't quite implement either correctly.

Make a lookup table given a die face, orientation, and direction of roll that returns the new correctly oriented die face.
Something about bitwise arithmetic I don't understand from answer #3 on this page. Seems like it could be harder to implement but possibly smaller, more elegant code. I don't, however, need anything to do with spinning or edges or animation, just fetching the next face up.

I'm trying not to prematurely optimize, but eventually the code should be able to be made as compact as possible. BASIC, so I'm not using any complicated 3D libraries or game engines, I want to keep this close to the bare metal as far as logical physics simulation goes.


texts: In unity, some part of mesh doesn't show only in play mode

texts:
This is screenshot of not playing mode. You can see the the speedloader and bullets inside of the revolver.

And this is when playing mode.

As you can see, I can see the speedloader and bullets in scene view, but not player's camera. Sometimes, it disappears in scene view either!

I made this model same as other weapons, but others are working fine. Only this weapon causes this problem. All weapons that I made are based on same model and rigs, and I kept the weapon's scale fit as same as possible.

I tried move the camera and scale down a little bit, but still couldn't saw.

Why this is happening? How do I solve this? Any advice will very appreciate it.


texts: OpenGL: Move camera regardless of rotation

texts:
For a 2D board game I'd like to move and rotate an orthogonal camera in coordinates given in a reference system (window space), but simply can't get it to work.

The idea is that the user can drag the camera over a surface, rotate and scale it. Rotation and scaling should always be around the center of the current viewport.

The camera is set up as:

gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(-width/2, width/2, -height/2, height/2, nearPlane, farPlane);

where width and height are equal to the viewport's width and height, so that 1 unit is one pixel when no zoom is applied.

Since these transformations usually mean (scaling and) translating the world, then rotating it, the implementation is:

gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();

gl.glRotatef(rotation, 0, 0, 1); // e.g. 45°
gl.glTranslatef(x, y, 0); // e.g. +10 for 10px right, -2 for 2px down
gl.glScalef(zoomFactor, zoomFactor, zoomFactor); // e.g. scale by 1.5

That however has the nasty side effect that translations are transformed as well, that is applied in world coordinates. If I rotate around 90° and translate again, X and Y axis are swapped.

If I reorder the transformations so they read

gl.glTranslatef(x, y, 0);
gl.glScalef(zoomFactor, zoomFactor, zoomFactor);
gl.glRotatef(rotation, 0, 0, 1);

the translation will be applied correctly (in reference space, so translation along x always visually moves the camera sideways) but rotation and scaling are now performed around origin.

It shouldn't be too hard, so what is it I'm missing?


texts: How to make a CD with audio and data at the same time

texts: I made a homebrew game and want to distribute it to my friends using CD's. The game uses CD Audio music and I already made a quick program to check if the disc is in the drive, but I don't know how to make a CD with audio and data and the same time. can anyone help me with this?


texts: How can I expose a property to Unity that should be treated like an asset path?

texts:
I want to be able to do something like this:

public FileInfo XmlBehaviourFile;

And then use the asset browser in the Unity editor to select an asset. Ideally, I would like to limit it to XML files but that isn't too important.

I am aware of TextAsset but I can only access either a string or byte array of the contents. I can probably make this work, but at the moment, my library takes a FileInfo and handles the reading itself.

Is there a Type I can use that will make Unity let me choose a file in the editor and then simply store the path (ideally, it would handle making sure the path is relative and including the asset in the build).

Alternatively, would it be possible to write such a type that would work, I've not extended Unity, but I am aware it is possible.


texts: Unity, tell matched players to go pick characters (Matchmaking)

texts:
I need to tell all the players in the match to go to some method that'd take them to character pick. The thing is that the pick happens inside the menu scene after the level get's preloaded (ascyncroneously). So the players stay in the same menu scene but they have to pick characters before the time runs out and the level itself starts.
Is it possible to do that in multiplayer using the matchmaker?
How can it be done if so?

Thanks in advance!


texts: Should I share the same tile structure for display and pathfinding?

texts:
I know how to display a 2D map with tiles.

I know how to make a pathfinding algorithm using A*.

Those two things demand a structure or a class. My question is : do you use the same structure for displaying and path-computing ? Node structure for pathfinding demand to add some data : x position, y position, F, G, H plus the Parent Node. Tile structure for displaying can be optimized to almost only one information : the value of the tile.

Do you use a big class for your tiles, that handle both displaying and pathfinding, or do you use a different method ? Thank you for your advices !


texts: What are some good (retro) symbols for magic/mana/energy?

texts:
Much like a heart is used a lot for health and lives in old retro games...

...what would be a good icon to use for Energy, Mana and/or Magic points?


texts: How to ensure Unity does not rearrange the sub-meshes of a mesh on import?

texts:
having a bit of a head scratcher problem here. I have my artist's making multiple unique meshes in Maya that contain 3 materials. Each material is assigned to a sub-mesh in a specific order. This order is identical across all the meshes being created. When bringing over these meshes to Unity, we have noticed that some meshes keep their material/sub-mesh order from Maya, and some do not. It's been making code generated material swaps a nightmare. So a few questions:
1.) What is Unity's logic when importing meshes and ordering the sub-meshes?
2.) Is there a simple way to make sure Unity does NOT reorder the sub-meshes/material order?
3.) Is there a way on Maya's side when exporting to make sure the sub-meshes/material order is as intended?
Any help or ideas is appreciated. Thanks!!


texts: How to fix Corner Collision with SAT algorithm?

texts:
I am making a platformer game, my way of handling collision works most of the times, but when I jump on a platform's corner I get pushed away, it probably happens because my function returns right or left respectively and not bottom collision. Is there anyway to modify this function to work, or is there another algorithm that works better?

public static string RectangleCollision(Rectangle r1, Rectangle r2) {
    string result;

    float w = 0.5f * (r1.Width + r2.Width);
    float h = 0.5f * (r1.Height + r2.Height);
    float dx = r1.Center.X - r2.Center.X;
    float dy = r1.Center.Y - r2.Center.Y;

    if (Math.Abs(dx) <= w && Math.Abs(dy) <= h) {

        // Collision
        float wy = w * dy;
        float hx = h * dx;

        if (wy > hx) {
            if (wy > -hx) {
                // Collision on top
                result = "top";
            } else {
                // On left
                result = "left";
            }
        } else {
            if (wy > -hx) {
                // on right
                result = "right";
            } else {
                // on bottom
                result = "bottom";
            }
        }

     } else {
         result = "false";
     }

     return result;
}
```


texts: What is the practical use of IBOs / degenerate vertex in OpenGL?

texts:
Vertices in 3D models CAN get cut in the process of optimizing 3D geometry, (degenerate vertices) by 3D graphics software (Blender, ...) when exporting because they aren't needed when reusing a vertex for multiple triangles.
(In the current case 3D data is exported from Blender as .ply and read by a simple application that displays the 3D model)

Every vertex has a few attributes like position, color, normal, tangent,...
But the data for each vertex that is cut through the vertex sharing is lost and is missing in the vertex shader.

Modern shader techniques like Bump or Normal mapping require normals/tangents per vertex which are also cut.

To use complex shader techniques IBOs must not be used? Or is there a way to use IBOs and retain the data per vertex that was origionally lost?


texts: For each array within array using UnityScript

texts:
I am trying to randomly generate some values for a character using Javascript in Unity.

I have two arrays, one for colour, and one for body type. I want to get one value out of each array, randomly, which so far I have achieved like this:

var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');

var colLen = colours.length;
var colour = colours[Random.Range(0,colLen)];

var bodLen = bodyTypes.length;
var bodyType = bodyTypes[Random.Range(0,bodLen)];

Debug.Log(colour);
Debug.Log(bodyType);

This works fine, however I would like to optimise it slightly, by putting the two arrays into another array and then using a loop to get each value. So far I have tried this:

var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');

var arrays = new Array(colours, bodyTypes);

for(var array in arrays) {
    var arrayLen = Random.Range(0, array.length);

    Debug.Log(array[arrayLen]);
}

This gives the error "Length is non a member of Object". Is there any way of achieving what I want to do? I am very new to any type of game development, so I don't really know the best way to go about it.


texts: Using Variable to Reference Different C# Script

texts:
I had a question about using a variable to access different scripts. I have a Rhythm game I'm working on, and I have different scripts named Rudement1, Rudement2, Rudement3, ect... One of my other scripts has something like this,

public GameObject HighHatFlare;
public int RudementNumber = TrainingMenuScript.TrainingMenuInt;

// Use this for initialization
void Start ()
{
    Rudement1.NoteCreated = Rudement1.NoteCreated + 1;
}

What I'm looking to do is use this same script but modify it to to something like this:

public GameObject HighHatFlare;
public int RudementNumber = TrainingMenuScript.TrainingMenuInt;

// Use this for initialization
void Start ()
{
    Rudement(RudementNumber).NoteCreated = Rudement(RudementNumber).NoteCreated + 1;
}

The goal is that I can continually use this script and it will modify itself as I use different "Rudement" scripts. I figured it some type of "RudementNumber" or 'RudementNumber', but I can't figure it out. Can someone help me with this?

A rudement is a basic sticking pattern that you learn at a very beginning level of drumming. Also spelt "Rudiment" I was always told to spell it with an "e" because of its French roots (not relevant).

In this context it could be replaced by the term "level". Each rudiment is a different level and therefore has different amounts of notes. The base script between each level is identical, but the note patterns are different.The script above is attached to each note to give them a numeric order as they are created. It is running under a mono behavior. I think that at it's simplest I'm wondering if you can reference a script name via a changeable string with the intent to pull a variable from it. As the level changes so does this string to pull the amount of NotesCreated from the new level.


texts: Performance of delta force-esque voxel terrain

texts:
I've been reading about voxel terrain lately and often see people asserting that it will absolutely kill performance.

What I don't understand is how games like Delta Force managed to have smooth voxel terrain without all these alleged performance issues? Sure, their terrain doesn't look cutting edge but it certainly doesn't (seem to) impose very harsh performance requirements.

Is Delta Force perhaps not actually using voxels for their terrain? How exactly does their engine work and why don't people use the same techniques today?


texts:
I'm trying to integrate a "ground particle" effect (like a fire-circle or similar) in Unity3d, however since i'm using uneven terrain as my terrain mesh, the effect gets culled behind terrain parts that above it.

To better ilustrate it I created an image as attachment :
I want for the effect to always be displayed regardless of it's "depth".
How can this undesired effect be avoided/resolved properly ?


texts: What is the delta value passed to the Screen's render method?

texts: The delta value given to the render method in the Screen class is a non-constant number. What is it? Where does it come from? Does it differ by screen size?


texts:
I am using a sensor as the input to my game.

When a certain level of force is exerted on the sensor, for a certain amount of time, I want the next level to be reached.

How would I do this?

I have attached both the timer code and the game code, but I don't know how to use them together.

Timer code:

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

public class Timer : MonoBehaviour
{
    public int timeLeft = 5;
    public Text countdownText;

    // Use this for initialization
    void Start()
    {
        StartCoroutine("LoseTime");
    }

    // Update is called once per frame
    void Update()
    {
        countdownText.text = ("Time Left = " + timeLeft);

        if (timeLeft <= 0)
        {
            StopCoroutine("LoseTime");
            countdownText.text = "Times Up!";
        }
        //Invoke("ChangeLevel", 0.1f);
    }

    IEnumerator LoseTime()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            timeLeft--;
        }
    }
    void ChangeLevel()
    {

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
}

Game code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;

public class arduino : MonoBehaviour {

    SerialPort sp = new SerialPort("\\\\.\\COM6", 9600);// Com port and the baud rate of the arduino
    Material m_Material;
    GameObject Sphere;

    void Awake(){
        Sphere = GameObject.FindWithTag ("Player");
        m_Material = GameObject.FindWithTag ("Player").GetComponent<Renderer > ().material ;
    }
    void Start ()
    {
        if (!sp.IsOpen)
        { // If the serial port is not open
            sp.Open(); // Open
        }
        sp.ReadTimeout = 250; // Timeout for reading
     }
    // Update is called once per frame
    void Update () {
        if (sp.IsOpen) { // Check to see if the serial port is open
            try
            {

                string portreading = sp.ReadLine(); // get the string output of the serial port
                float amount = int.Parse(portreading);

                if ((amount > 10f) && (amount < 100f))
                {
                    m_Material.color = Color.grey;
                   // Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));

                }

                if ((amount > 101f) && (amount < 150f))
                {
                    m_Material.color = Color.blue;
                    //Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));
                }

                if ((amount > 151f) && (amount < 201f))
                {
                    m_Material.color = Color.yellow;
                    //Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));
                }
                if ((amount > 201f))
                {
                    m_Material.color = Color.red;
                   // Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));

                }
            }
            catch (System.Exception)
            {

            }
        }
    }
}


texts: Is using events a good way to have the option to return out of a method or alter its normal execution?

texts:
Let's say I have a script that calls a method frequently, and when doing so wants to allow other objects to know about it and potentially alter what happens in that method. This is fairly simple to do using C# events:
public class PassByReference
{
    public bool foo;

    public PassByReference(bool foo)
    {
        this.foo = foo;
    }
}

public class Example : MonoBehaviour
{
    public event Action<PassByReference> OnSomethingHappened;

    private void DoSomething()
    {
        var returnOut = false;

        // Do some stuff

        var passByReference = new PassByReference(returnOut);
        OnSomethingHappened?.Invoke(passByReference); // Some other object can read and alter this

        if (passByReference.foo)
            return;

       // Do some more stuff
    }
}

Is this a good way to do things if one anticipates that, based on a combination of the information given by the event, and their own properties, other objects may want to stop the second half of the Example method from running (or maybe alter what happens)? I guess what I'm trying to do is prevent the Example class from having to store references to many other classes that will interact with it only occasionally, and clog up the method with many if statements. My main concern, though, is that frequently creating new classes to pass data via reference in the event(s) can lead to performance issues, especially if many objects in my game are using the Example script.


texts: How to change colors of texture in lwjgl?

texts:
I have the following texture:

The black pixels are characters, the background is transparent.
How do I change the black pixels of the characters to another color?
I use this texture as a bitmap for text rendering in lwjgl. For example, is there a way to change the black pixels to red?
I looked to shaders, but I don't know how to use shaders and what they does.
I would appreciate an example.
I also looked at this page.

But I don't really understand how to do it.
I will really vote up your answer.


texts: Different revenue models between developers and publishers?

texts:
I am working at a small game studio developing games for iOS and Android. We do the full journey here, from idea to finished product and we have funding to do so. However, with the smartphone market being a bit of a lottery for small developers we are looking into getting into a publisher deal.

What I am wondering now is what kind of different deals one could look at. From what I have gathered from reading a number of articles a common model it is that the publisher pay for the development cost and once the game is released the developer gets about 20% of the revenue. What I am wondering is if there are any other common models used between developers and publishers?


texts:
My game-loop looks like this:

        public void run() {
            init();

            final double amountOfTicks = 60.0;
            double ns = 1000000000.0 / amountOfTicks;
            long time = System.currentTimeMillis();
            long lastTime = System.nanoTime();
            long now = 0;
            double delta = 0;
            int tickCount = 0;
            int renderCount = 0;

            while(running) {

                now = System.nanoTime();
                delta += (now - lastTime) / ns;
                lastTime = now;

                if(delta >= 1) {
                    tick();
                    tickCount++;
                    delta--;
                    render();
                    renderCount++;
                }

                if(System.currentTimeMillis() - time >= 1000) {
                    time += 1000;
                    System.out.println(tickCount + " Ticks, " + renderCount + " FPS");
                    tickCount = 0;
                    renderCount = 0;
                }

            }
            stop();

        }

In the variable "amountOfTicks" i can set how many ticks i want per second. The amountOfTicks are here the same as the fps which i have. With this solution my console prints "60Ticks, 60 FPS", but the problem is, that the CPU-performance with this method is too low. I have only 60 Ticks and only 60 FPS, but the whole while-loop is still running through as fast as my pc can.

The only thing how i can improve the cpu-performance is, if i let the thread for 1ms or so sleeping. But is this solution not dirty? This solution will maybe work on my (relative good pc), but on a other with with less CPU-performance the 1ms sleep maybe are waste, because of this the game maybe can not reach the 60FPS of this?


texts: Why is my program "not responding" when I run it?

texts:
I'm trying to learn to code with python and while using pygame, I came across this: every time I run the window it says "not responding".

Specifically, it happens when I click to drag the window; the title changes to "not responding" and I do not know what to do.

Here is all of my code:

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Game Test")


texts: Character implementation and architecture

texts:
Me and a friend are trying to make an RPG in Java, while we are learning the language, and we have been discussing the character implementation. We would like to know which is the best solution in computational and expanding criteria s.

The game will be something like Final Fantasy 6. We would have a lot of different characters, each having their own stats and 3 different abilities. The stats would change frequently, and be saved for future reference. It's not supposed to have two identical characters.

Option 1: My idea defends that there would be a class "Hero", and a class to every character that would extend Hero. For example, if I have 10 characters, there would be 10 classes that extend "Hero". This character class would contain all variables concerning stats  and a method for each ability. We would implement a singleton pattern, to assure there is only ever one instance.

Option 2: For my friends idea, the object "Hero" would have several attributes, the more important ones being for name, stats and character class. While name and stats can be summarized as simple variables, a character class is manifested as an object of its own  tied to a specific hero. In short, an instance of a character class is bound only to one "Hero", but many heroes can have a common character class. For example, Josh and John can both be "Fighters", but they don't share the same instance of the character class object; they're just similar in functionality.

A "Hero" must have a character class in order to work properly, therefore his creaion would demand his own name and the name of a character class.

This method guarantees much higher flexibility when it comes to creating heroes, since the use of generic character classes (having many "Fighters" in a party, for example) becomes possible; in fact, this idea of character classes can be expanded for use with enemy units. However, it will require a bit more processing power.


texts: Desaturate texture using mask in OpenGL 2

texts:
I have a very large texture i am using as background and i want to apply a filter to a small part of it, the "small part" is defined by the alpha layer of another texture i have (which is still RGB8888), i am not sure what's the best approach to do this. I'd like to keep the same (very simple) shader i am already using for other sprites, which is similar to the basic one, i.e.:

precision mediump float;
uniform sampler2D uTexture;
varying vec2 vTexPos;
void main() {
  gl_FragColor = texture2D(uTexture, vTexPos);
}

So, i have some questions

How can i apply my filter only to "masked" region and avoid drawing others?
Do i have any performance loss if i draw the big texture again once loaded to just apply it to a small portion of the screen?
Can i map a second texture to the shader and use something like "if uTexture2 != null" -> apply as mask? Will this give me any performance gain compared to using a second shader?
Both textures are premultiplied, how should i handle alpha masking?

What id like to do is something like this (original, mask, result):

My environment is Android 4.0, im using GLES20.


texts:
I was looking for some beginner advice regarding level design across multiple resolutions.

I believe the answer is likely "it depends", but any input from anyone with real experience is very appreciated.

Basically, I am building a 2D Super Metroid type game. If rooms/levels are to be a tiled grid, what are some general best practices for designing rooms when taking into account different resolutions?

Since more or less tiles could fit vertically on a single screen depending on the resolution, is it better to design towards possibly having more of the room visible depending on the screen (with a bare minimum needed for gameplay), or should I fix the design at a certain tile height and scale the graphics?


texts:
I was trying out a shadowmap. But all my shadow is white. I think there is some problem with my homogeneous component. Can anybody help me? The rest of my code is written in xna

Here is the hlsl code I used

float4x4 xWorld;
float4x4 xView;
float4x4 xProjection;

struct VertexToPixel
{
float4 Position         : POSITION;
float4 ScreenPos        : TEXCOORD1;
float Depth : TEXCOORD2;
};
struct PixelToFrame
{
float4 Color            : COLOR0;
};

//------- Technique: ShadowMap --------
VertexToPixel MyVertexShader(float4 inPos: POSITION0, float3 inNormal: NORMAL0)
{
VertexToPixel Output = (VertexToPixel)0;

float4x4 preViewProjection = mul(xView, xProjection);
float4x4 preWorldViewProjection = mul(xWorld, preViewProjection);
Output.Position =mul(inPos, mul(xWorld, preViewProjection));
Output.Depth = Output.Position.z / Output.Position.w;
Output.ScreenPos = Output.Position;

return Output;
}

float4 MyPixelShader(VertexToPixel PSIn) : COLOR0
{
PixelToFrame Output = (PixelToFrame)0;

Output.Color = PSIn.ScreenPos.z/PSIn.ScreenPos.w;

return Output.Color;
}

technique ShadowMap
{
pass Pass0
{
    VertexShader = compile vs_2_0 MyVertexShader();
    PixelShader  = compile ps_2_0 MyPixelShader();
}
}