texts:
good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction.

Why is this happening and what is the solution?

Pressing two buttons moves to the left and the shape changes.

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

public class PlayerKontrol : MonoBehaviour {

public float karakterHizi = 8f, maxSurat = 4f;
private Rigidbody2D myRigidbody;
private Animator myAnimator;

private bool solaGit, sagaGit;

void Awake () {
    myRigidbody = GetComponent<Rigidbody2D> ();
    myAnimator = GetComponent<Animator> ();

}

void FixedUpdate () {
    if (solaGit) {

        SolaGit ();
    }

    if (sagaGit) {

        SagaGit ();
    }
}

public void AyarlaSolaGit (bool solaGit)
{
    this.solaGit = solaGit;
    this.sagaGit = !solaGit;
}

public void HareketiDurdur () {
    solaGit = sagaGit = false;
    myAnimator.SetBool ("run", false);
}

void SolaGit (){

    float Xdurdur = 0f;
    float surat = Mathf.Abs (myRigidbody.velocity.x);

    if (surat < maxSurat)
        Xdurdur = -karakterHizi;

    Vector3 yon = transform.localScale;
    yon.x = -0.3f;
    transform.localScale = yon;

    myAnimator.SetBool ("run", true);

    myRigidbody.AddForce (new Vector2 (Xdurdur, 0));

}

void SagaGit () {

    float Xdurdur = 0f;
    float surat = Mathf.Abs (myRigidbody.velocity.x);

    if (surat < maxSurat)
        Xdurdur = -karakterHizi;

    Vector3 yon = transform.localScale;
    yon.x = 0.3f;
    transform.localScale = yon;

    myAnimator.SetBool ("run", true);

    myRigidbody.AddForce (new Vector2 (Xdurdur, 0));

}

}


texts: Generated Perlin noise is not coherent (sharp edges)

texts:
I'm having a bit of trouble implementing Perlin Noise, I've included an example the problem below. I've tried debugging but everything appears to be working correctly, and I can't figure out what's causing the sharp edges in the output.

Below is a snippet of the code that I'm using to generate the noise (sorry about lack of comments, most should be self-explanatory though).

inline int ffloor(float i)
{
    return (i >= 0 ? (int)i : (int)i-1);
}

inline float dot(float x, float y, Vector grad)
{
    return (x * grad.x + y * grad.y);
}

inline float lerp(float t, float a, float b)
{
    return a + t * (b - a);
}

inline float scurve(float t)
{
    return (t*t*t*(t*(6*t -15) + 10));
}

inline Vector getVec(int x, int y)
{
    unsigned char a = permutations[x & 255];
    unsigned char b = permutations[y & 255];
    unsigned char val = permutations[(a + b) & 255];
    return gradients[val];
}

float noise2(float xPos, float yPos)
{
    float x0 = ffloor(xPos);
    float x1 = x0 + 1.0f;
    float y0 = ffloor(yPos);
    float y1 = y0 + 1.0f;

    float fracX = xPos - x0;
    float fracY = yPos - y0;

    float n00 = dot(fracX, fracY, getVec(x0, y0));
    float n01 = dot(fracX, fracY - 1.0f, getVec(x0, y1));
    float n10 = dot(fracX - 1.0f, fracY, getVec(x1, y0));
    float n11 = dot(fracX - 1.0f, fracY - 1.0f, getVec(x1, y1));

    float sx = scurve(fracX);
    float sy = scurve(fracY);

    float avgX0 = lerp(sx, n00, n11);
    float avgX1 = lerp(sx, n01, n11);

    return lerp(sy, avgX0, avgX1);
}

void init(void)
{
    int i, j, k;
    float step = 6.24f / 256;
    float val = 0.0f;

    for (i = 0; i < 255; i++)
    {
        permutations[i] = rand() & 255;

        gradients[i].x = (float)sin(val);
        gradients[i].y = (float)cos(val);
        val += step;
    }

}

To generate the noise map I'm calling init and then iteratively calling the noise2 function with coordinates that have been scaled to the size of the map I want (so xPos and yPos are always between 0 and 1).


texts: Which part of the rendering pipeline compiles shaders?

texts:
Generally, video games and other graphical software that use vertex and fragment shaders will have said shaders in the form of actual shader source code (typically in glsl or hlsl), and will compile them for use with the display hardware at runtime. (It is my understanding that shaders cannot really be precompiled into the game binary because the actual shader machine code that the display hardware uses depends on the graphics card brand and even its model/generation, and they may well be incompatible with each other.)

Even though I do myself work on the game programming field and use shaders, I actually don't know exactly which part of the graphics pipeline actually compiles the shaders into the machine code that the graphics card uses. Compiling shaders is essentially a black box: Throw the shader source code into whatever library you are using, and it does its magic behind the scenes.

I would be interested in knowing exactly where this compiling process happens. Which exact part of the entire system takes the shader source code and produces shader machine code from it?

My (wild) guess is that this is done by the graphics card driver (because the driver knows what kind of machine code it should output, and how to optimize it, for the particular brand and model of graphics card).

(If this is indeed so, it would explain at least partially why the graphics driver is so crucial in how efficiently games run, as its optimization of the shader machine code would have great impact on rendering speed.)

Are there any resources out there were I could find more info, in general, about these things?


texts: Can't correct perspective of Main Camera in Unity 3D without losing field of view

texts:
I have been trying to create a space based rails shooter game following a particular online course and I find a tilt(roll) on my spaceship as I move it towards the left and right ends of the screen.

https://imgur.com/Kkg8hp2
(A normal screenshot of my spaceship at default position)

This is due to perspective of the camera as I have been told and apparently dragging the camera farther behind the spaceship and decreasing its field of view helps.

https://imgur.com/0oXJff7
(The tilted spaceship when it's at an end of the game window)

But, doing that neutralizes the illusion of speed caused by a greater field of view. I have found a middle point between the two to balance both aspects of the game but I would like to know if there is any way to get higher field of view without making the ship look like it's tilted.

Things I have considered doing:

Added a positionRollFactor which gives the ship some additional roll in the opposite direction of the tilt. (This still doesn't fix the perspective issue in which one half of the ship is more enlarged than the other).
Tweaking the field of view by trading off a little of each feature.


texts:
I have my coin image in the assetLoader class, then I import it into gameWorld.

My question is, how can I draw() rows of coins without having to write out 15 different coins?

i.e., coin1, coin2, coinRect1, coinRect2, coinX1, coinX2, etc.
Wouldn't it be more efficient/easier on memory&performance to create a 'coin' class and use a loop somehow?

It's a vertical scroller so the coins should be lined up vertically and disappear individually as the playerRect intersects the coinRect.

The coins should not intersect the obstacles and the randomly generated number of coins in any row (e.g. a row of 6 coins all lined up) should be between 1 and 10.
If I used a loop (somehow...) the integer i would be the randomly generated number of coins in any row, so that 1<=i<=10, and if coin.position intersected obstacleRect then it i would become i-1 so that the coins stopped right before the obstacle.


texts: Saving instances of classes, then recreating the instances

texts:
I have many types of entities, each type has a lot of if instanceof Spider (for example ) then do this in the game code... Now I got to the part where I want to save each type.

They all are based on the same class, Entity but implement some of their own methods.
When I save them, lets say for now I just want their position and their health.

So I do write position the write health, to a file with all the entities.

Now here is the problem, When I want to load it, How will I know it's a spider and then create a Spider instance?

An easy fix is to create toString method then writing it before the position and health. But the problem with this is that when I load I will have to have this big switch statement for each type and I will have to manually add the case for a new type that I create. This is not very mod friendly.

What would be a way to read a name of a class and then create an instance of that class without having a big switch case?


texts: What should I wear to a job interview with a game development company?

texts:
Many game development companies are less formal in terms of workplace attire than other types of software development houses. For example, I know that one place at which I will be interviewing soon has a predominant workplace culture of jeans and polos or t-shirts.

Should I wear a suit? Shirt and tie? Shirt and sport jacket, with or without tie? I want to show that I'm serious about the job, but that I understand the culture, too.


texts: How can I transfer this code (originally for FPS template) for use in a Third Person Template?

texts:
I learned how to create a blueprint for making a character be able to pick up and drop objects:

It did not work, and I believe the reason is because it was originally made to work for the FPS template that Unreal comes with.  I decided to use the Third Person template, and I think that's why it's not working.
Am I correct?  What blueprint coding should I be looking at?  What's missing, or what's preventing this from working?
Thanks!


texts: How do I make gameobject flip and change position when player is facing left?

texts: I attached a  a gameobject labeled "Gun" to my player's back and when the player is facing left I want the Gun to continue to look like it's still attached to his back. Right now when I play the game and the player is facing left, the gun stays in the same position it was in regardless of what direction the player is facing. How do I make the gun look like it's still on the players back if facing left? (sorry if it sounds like idk what i'm doing... I'm sorta new to game dev.)


texts: How do I determine the position of one vector relative to another?

texts:
I'm making a game for Kinect in Unity which tracks hand movements. I have the player's root position and the position of their fist stored as 3-dimensional vectors (Vector3 in Unity), but they're both in world space.

How can I determine the location of the player's fist relative to their root position?


texts:
Do I need to use SteamWorks in my game to have it on steam? The website talks about it however it does not state it is necessary so I am asking if it is.

I am not asking how to do it I'm asking if I need to do it.


texts:
I am trying to implement dynamic environment mapping in my OpengGL rendering engine for the purpose of showing reflections. I am following the tutorial found here. This tutorial (and many others that I have seen) focus' on static environment mapping where you already have a cubemap made from texture data.

From what I gather, to perform dynamic environment mapping you would perform the following steps:

create a single cubemap texture that we can reuse
for each mesh:
    render the scene 6 times (or once using geometry shader) to fill faces of cube map from the perspective of mesh
    sample cubemap to render reflections on mesh

or perhaps it should be:

for each mesh:
    create a cubemap texture for mesh
    render the scene 6 times (or once using geometry shader) to fill faces of cube map from the perspective of mesh

for each mesh:
    sample cubemap to render reflections on mesh (using this meshes cubemap)

My question is whether this is the right general idea? In particular do you need to render your scene to a cubemap for each mesh that you want to have dynamic reflections on? If so this would seem to be exceedingly expensive for any scene with more than a few meshes receiving dynamic reflections. The only examples/tutorials that I have seen involve only one mesh that uses dynamic environment mapping.


texts: Addressable Asset Loading with Queue And Coroutine

texts:
I have around 17000 addressable assets (prefab) tiles that I am loading near the position of the camera.
Here is my algorithm

Get all Reference of the 17000 tiles in the array
Loop through the array and get the tiles that are within the proximity of my Player and queue It.
Based on the first enqueue item, start downloading the tiles with Addreessabl.Instantiate. Load one by one and wait for the first item download to finish.

here is the main loop that is doing the work:
 public IEnumerator StartDownloading()
    {
             isDownloadStarted = true;
        while (singleAbLoader.Count > 0)
        {
            SingleADLoader singleAbLoaderCurrent = singleAdLoader.Dequeue();
            if (abLoaderUnloaderManager.GetTilesWithinPlayerRange(singleAbLoaderCurrent) == true){

                Debug.Log("Starting to call " + singleAbLoaderCurrent.gameObject.name);
                yield return singleAbLoaderCurrent.DownloadAB();
                Debug.Log("Finsihed to call " + singleAbLoaderCurrent.gameObject.name);
                loadingSlider.value = sliderIncrementValue;
            }else
            {
                Debug.Log("escaping the download" + singleAbLoaderCurrent.name);
                yield return null;
            }
        }

        isDownloadStarted = false;
    }

whereas the DownloadAD()
public IEnumerator DownloadAD()
{
    AsyncOperationHandle<GameObject> handle = Addressables.InstantiateAsync(prefabToLoad);
    yield return handle;
}

The tiles are loading fine but the problem is they are way too slow. I mean it takes much time to load tile.


texts: Draw multiple triangle strips in one draw call DirectX

texts:
I'm running into a bottleneck where I'm drawing many basic disconnected colored triangle strips in DirectX 9 (XNA). The problem comes with drawing them all in seperate draw calls, so I'd like to batch them all together into a single buffer and draw them in one draw call.

I understand that in DirectX10 and above, there's a way to draw many triangle strips in the same draw call by inserting a special "cut" index (-1) into the index buffer after every line strip.

Is there a way to do this without the use of the cut index? (Which as far as I know, isn't present in directx 9?)


texts: How can I set the rotation of a shape to the same as my image?

texts:
The way you set rotations of images is different from setting shape rotations.
So how can I make the shape have the same rotation as my image?

This is how my image rotates:

if(input.isKeyDown(Input.KEY_RIGHT))
        {
            rotate += rotateSpeed * delta;
            image.rotate(rotate - image.getRotation());
        }

How can I get the same effect but with a shape?

For example:

How can I get that rectangle to be at the same rotation as the car?


texts:
I'm attempting to develop an orthogonal game with lwjgl 3 and OpenGL in Eclipse, but I can't find an answer for rendering objects in 2D or 3D. Are both applicable? And if so what are the advantages of either one?
I would also like to rotate my camera if that changes your answer.


texts: Should I go with SpriteBatch or just 3D with Z component always zero?

texts:
I'm designing a platformer and beginning to code the viewing engine of the game. Now, I have to make a key decision: Should I just use SpriteBatch to draw all the 2D stuff, as there is no 3D, or should I just go with making camera-facing polygons with Z set to zero? What are the good sides and drawbacks of both? Performance? Extensibility?

Performance is a key factor as I'll be having lots of texttures/objects/effects/animations etc, and I'll be targetting high resolutions like 1920x1200 (if available on client's computer), so I need things to go smooth. On the other hand, I also need some extensibility, as I want to have great control over the drawing methods. Seems like I'd be going with 3D/polygon method, but I was wondering if it has any side-effects?


texts: Unity: Restrict movement inside a gameobject (2D)

texts: I've been sort of trying my own thing but it's super buggy so I'd like to see what other people have done to create moveable spaces. In essence, I just want to restrict my character's movement to inside of a sprite. So one of my sprites is the character  and another one of my sprites is a box -- I want to make it so my character can't leave the box. I've been modifying transform.position on mouse click in order to move my character, but now I'm not sure if this was the smartest idea.


texts: How can I handle fighting game collisions for complex animations?

texts:
Imagine that I have an animation like this.

As you can see, this attack hits in three horizontal places.
The opponent facing this player could be hit mid and low (standing or crouching).

The same goes for this move:

If the opponent is crouching, standing or in air it gets hit because the fire circle hits all areas (low, mid and high)

How can I handle hit detection with this sort of animation?


texts:
I'm following a book I bought on Google Play that is teaching me the ropes of MonoGame, and in Chapter 2 it introduces creating an input wrapper that takes care of all the input methods for a game pad or keyboard. What's supposed to happen is that the WASD keys is mapped to the same inputs that the right thumb-stick would be on the game pad, but what happens for me is that the WASD keys move up and down correctly, but on the game pad it is flipped for some reason. I've looked over every line that I think would cause the problem, even replacing my code with the source code in the book, and the project they provide as an example works perfectly, but my project using THEIR code does not. If anyone can look over my project and see what the problem could be, that would be awesome!

Project: Here

MonoGame Book (Would Recommend So Far): Here


texts: Hierachical Z-Buffering for occlusion culling

texts:
I'm reading the Occlusion Culling section in Real-Time Rendering 3rd Edition and I couldn't understand how it works. Some questions:

How does having a "Z-pyramid" contribute? Why do we need multiple resolutions of the Z-buffer? In the book, it's displayed as follows (left side):

Is the Octree structure the same Octree that is used for general frustum culling and rendering? Or is it a specialized Octree made just for the occlusion culling technique?
A more general question: In a previous section (and also here), the Occlusion Query term is described as "rendering a simplified bounding-volume of an object and comparing it's depth results to the Z-buffer, returning the amount of pixels that are visible." What functions in OpenGL are associated with this Occlusion Query concept?
Is this technique the standard for open-world games occlusion culling?


texts: Geometric Transformations on the CPU vs GPU

texts: I've noticed that many 3d programs normally do vector/matrix calculations as well as geometric transformations on the CPU. Has anyone found an advantage in moving these calculations into vertex shaders on the GPU?


texts: How can I once run For Loop in void OnGUI?

texts:
I want once run GUI on screen same Initialization a number.
I try say my think In easiest way then please payattention to this code:

using UnityEngine;
using System.Collections;

public class guimanager : MonoBehaviour {
    public bool Isdone;
     void OnGUI()
    {
            for (int j = 0; j <= 100; j+=20) {
            if (Isdone == true) {
                break;
            }

            GUI.Box(new Rect(j, j, Screen.width/2, Screen.height/2), "This is a test");
                print (j);
            }
        }
    }

I want keep my GUI.Box When end loop,So I need a boolean that when finish stop loop.

my problem Is frequent loop:

0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5,......

GUI.Box will Show

but When I want break my loop:

0,1,2,3,4,5

GUI.Box won't Show!!!!

Can I show my GUI.boxes In my loop when finished?

using UnityEngine;
using System.Collections;

public class guimanager : MonoBehaviour {
    public bool Isdone;
     void OnGUI()
    {
            for (int j = 0; j <= 100; j+=20) {
            if (Isdone == true) {
                break;
            }

            GUI.Box(new Rect(j, j, Screen.width/2, Screen.height/2), "This is a test");
                print (j);
            }
Isdone = true;
        }
    }

Why when I stop loop GUI.Box won't show!!!


texts: TypeError: unsupported operand type(s) for /: 'tuple' and 'int' Error

texts:
I wanna make a sprite appear on my cursor. However, I get this error:
Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\Tap Simulator\main.py", line 60, in <module>
    screen.blit(hitmarker, (pygame.mouse.get_pos() - hitmarker.get_size() / 2))
TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

screen.blit(hitmarker, (pygame.mouse.get_pos())) makes it appear right bottom of your cursor, so don't try it.
Source code:
import pygame, sys, time
from pygame.locals import *
from millify import millify,prettify

pygame.mixer.init()
pygame.init()
music = open("music.txt", "r+")
pygame.mixer.music.load("soundtrack.wav")
x = int(music.read())
WHITE = 255,255,255
font = pygame.font.SysFont(None, 44)
cpsecond = open("clickpersecond.txt", "r+")
cps = int(cpsecond.read())
baltotal = open("totalbal.txt", "r+")
totalbal = int(baltotal.read())
totalbalM = prettify(totalbal, '.')
clock = pygame.time.Clock()
w = 800
h = 600
screen = pygame.display.set_mode((w,h))
pygame.display.set_caption('Tap Simulator')
Loop = True
background = pygame.image.load("Background.jpg")
egg = pygame.image.load("egg.png")
resized_egg = pygame.transform.scale(egg, (282, 352))
text = font.render(f'Your total clicks are {totalbalM}', True, WHITE)
pygame.mixer.music.play(-1,0.0)
volume = pygame.image.load("volume.png")
mute = pygame.image.load("mute.png")
resized_volume = pygame.transform.scale(volume, (100, 100))
resized_mute = pygame.transform.scale(mute, (100,100))
icon = pygame.image.load("ico.ico")
hitmarker = pygame.image.load("hitmarker.png")
resized_hitmarker = pygame.transform.scale(hitmarker, (50, 50))

pygame.display.set_icon(icon)

while Loop:
    for event in pygame.event.get():
        if event.type == QUIT:
            Loop = False
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1: # 1 == left click
                egg_rect = resized_egg.get_rect(topleft = (260,150))
                vol_rect = volume.get_rect(topleft = (700,500))
                if vol_rect.collidepoint(event.pos):
                    x += 1
                    if x > 2:
                        x = 1
                if egg_rect.collidepoint(event.pos):
                    totalbal += cps
                    totalbalM = prettify(totalbal, '.')
                    screen.blit(background, (0,0))
                    if x == 1:
                        screen.blit(resized_volume, (700,500))
                    if x == 2:
                        screen.blit(resized_mute,(700,500))
                    screen.blit(text, (235,557))
                    screen.blit(resized_egg, (260,150))
                    screen.blit(hitmarker, (pygame.mouse.get_pos() - hitmarker.get_size() / 2))
                    pygame.display.flip()
                    text = font.render(f'Your total clicks are {totalbalM}', True, WHITE)
                    print("Your total clicks are", totalbalM, end="\r")
                    time.sleep(0.07)

    #print(pygame.mouse.get_pos()) #to get mouse pos
    screen.blit(background, (0,0))
    screen.blit(resized_volume, (700,500))
    if x == 0:
        screen.blit(background, (0,0))# [...] draw something different
    elif x == 1:
        pygame.mixer.music.unpause()
        screen.blit(resized_volume, (700,500))
    elif x == 2:
        pygame.mixer.music.pause()
        screen.blit(background, (0,0))
        screen.blit(resized_mute,(700,500))
    screen.blit(text, (235,557))
    screen.blit(resized_egg, (260,150))
    pygame.display.flip()
    pygame.display.update()
    clock.tick(30)

with open("totalbal.txt", "w") as baltotal:
    baltotal.write(str(totalbal))
baltotal.close

with open("music.txt", "w") as music:
    music.write(str(x))
music.close
pygame.quit()
sys.exit()


texts: Ray->triangle collision math seems to not work?

texts:
First time asking, pardon any mistakes I make :)

I am programming a game from scratch, and the collision detection is giving me issues. I have AABB in place to check proximity, and if that reacts, the two models are checked by having each vertex in the moving model be a line going from the vertex' current position to its intended position. That line then gets checked against each triangle polygon in the 'obstacle' model.

My (current...) problem is that the math seems to react wrongly in the early part of that ray-triangle check (code below). I try simply to see if the two ends of the ray (vertex origin and vertex destination) are on opposite sides of the polygon plane (if they are not, the ray could not possibly be going through the polygon). I do this by getting a (not yet normalized) normal from the polygon via cross product. Then I dot the ray ends' positions with that. If it's one positive and one negative dot product, they should be on either side. Problem is, that never happens, even when i run models right through each other in tests. Never a 'positive & negative' result.

Can anyone spot my mistake(s)??

Code:

double Dot(Vec3 *a, Vec3 *b)
{
    double d = a->v[0] * b->v[0] + a->v[1] * b->v[1] + a->v[2] * b->v[2];
    return d;
}

Vec3 CrossProduct(Vec3 *a, Vec3 *b)
{
    Vec3 v;
    v.set(
        a->v[1]*b->v[2] - a->v[2]*b->v[1],
        a->v[2]*b->v[0] - a->v[0]*b->v[2],
        a->v[0]*b->v[1] - a->v[1]*b->v[0]
    );
    return v;
}

bool Collide(Vec3 *a, Vec3 *b, int target, int p)
{
    // a and b are the ray points in global space
    // target is the index number of the obstacle model
    /// p is the triangle polygon being checked (in a loop not included here)
    Vec3 poly_vert[3] = {entities[target].vertex[entities[target].poly[p].vertex[0]].pos
                    ,entities[target].vertex[entities[target].poly[p].vertex[1]].pos
                   ,entities[target].vertex[entities[target].poly[p].vertex[2]].pos};
    // poly_vert is the three vertices of the triangle polygon
    // Subtractions so poly_vert[0] essentially becomes the 0,0,0 center of the universe
    Subtract(&poly_vert[2],&poly_vert[0]);// Essentially, the vector from
                                             polyvertex 0 to polyvertex 2
    Subtract(&poly_vert[1],&poly_vert[0]);// Essentially, the vector from
                                             polyvertex 0 to polyvertex 2
    Subtract(a,&poly_vert[0]);
    Subtract(a,&entities[target].pos);// Make it relative to the obstacle model
    Subtract(b,&poly_vert[0]);
    Subtract(b,&entities[target].pos);// Make it relative to the obstacle model

    Vec3 poly_cross;
    poly_cross = CrossProduct(&poly_vert[1],&poly_vert[2]);
    double da = Dot(a,&poly_cross);
    double db = Dot(b,&poly_cross);

    if (da*db >= 0){return false;}
    return true;
}


texts: Ease Rotate RigidBody2D toward arbitrary angle

texts:
I'm trying to make a rigidbody2D circle return to an orientation after a collision. But there is a weird behavior I do not expect - it always orients to the same direction.

This is what I call in FixedUpdate():

rotationdifference = -halfPI + rigidbody2D.rotation;
rigidbody2D.AddTorque (rotationdifference * ease);

I would expect this would rotate 90 degrees (1/2 Pi Radians) off of the neutral axis. But it does not. In fact it performs exactly the same as:

rotationdifference = rigidbody2D.rotation;
rigidbody2D.AddTorque (rotationdifference * ease);

What is going on? How would I be able to set an angle I want it to ease towards, and then have it ease towards it when its not colliding with some other force?

=====

Edit

For those who want to try this themselves, here is a MonoBehavior. Apply it to a sprite with a rigidbody2D.
I have a boxcollider going througha  field of pegs like in pachinko.

using UnityEngine;
using System.Collections;

public class MarchingMovement : MonoBehaviour {

public Vector2 speed = new Vector2(50, 50);
public float ease = 0.01f;
private float rotationdifference;
private float halfPI = 1.57079632679f;
// Use this for initialization
void Start () {
    //rotationdifference = 3.0f;
}

// Update is called once per frame
void Update () {

}
void FixedUpdate()
{
    // 5 - Move the game object
    rigidbody2D.velocity = speed;
    rotationdifference = -halfPI + rigidbody2D.rotation;
    rigidbody2D.AddTorque (rotationdifference * ease);
}
}


texts: Is there a better way to handle a large amount of organized game data in Character Creation?

texts:
I am currently working on a text based prototype, in where the player is (eventually) allowed to have over 180 character choices in a quickly played permadeath type of game. It's a lot simpler than it sounds, based on a sort-of component system where the player choices several components, which can result in so many character types. However, each character type is distinctly defined, tagged, and marked with data for a very specific reason. So there may be a lot of different "Orcs" the player could create, they are each defined in game data individually with their respective changes to the base character.

Right now, the game only has about 4 character choices. This is easily handled in code, without any save/loading of files, or accessing of databases, or any fancy classes.

In many text based games, it is all handled in code, perhaps with a simple switch. Input choice: 1 = Human, 2 = Elf, 3 = Orc, 4 = Minotaur, etc. etc.
However, this tends to get ugly when there are 180 possible choices. It gets uglier with nested switches.

I want to be able to have players filter the vast number of choices, with something like a GUI search bar or checkbox options. "[ X ] Melee Based, [  ] Uses Spells, [ X ] Uses Stealth."
Even simpler, perhaps a button for players who need help choosing, or suggestions based on a few questions for new players. "Are you big on Swords or Sorcery? blah blah" Alright, we suggest you try a: Elven Fire Wizard.

Besides hard coding this information which is what I am currently planning, is there a more organized way to handle search queries, the process of elimination, filtering of results, or any other thing I might need to help ease players into choosing from what will certainly be an overwhelming number of possibilities?
Even if newbies are only given a small number of choices that are easy to grasp, even expert players will need some sort of filtering system to help them decide.

As a developer, I enjoy having my code easily accessible. Reading through nested control structures to edit information isn't my favorite way of handling it. However, right now it's certainly the easiest since I only have 4 character choices.
I am entirely ignorant on databases, so forgive my ignorance if I mentioned that.

I am not exactly sure if a "database" is overkill or not for game data like this. Especially game data that doesn't need to be accessible to anyone but the developer, and is only very large after a significant amount of time has passed to update the game hundreds of times.


texts: Why is Random.Range(0,3) generating only 0, 1 or 2 when 3 is supposed to be inclusive?

texts:
I'm currently having trouble getting my head around how Random.Range() and Array[].Length are working in the script below.
public class SpawnManager : MonoBehaviour
{
    public GameObject[] animalPrefabs;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.S))
        {
            int animalIndex = Random.Range(0, animalPrefabs.Length);
            Instantiate(animalPrefabs[animalIndex], new Vector3(0, 0, 20), animalPrefabs[animalIndex].transform.rotation);
        }
    }
}

Here, animalIndex is being assigned by Random.Range() a random number between 0 and the animalPrefabs[] array's length, which is 3. According to the documentation (both Visual Studio's and Unity's), both the minimum and maximum Random.Range() numbers are inclusive, which means Random.Range()'s possible outputs would amount to 4 numbers (0, 1, 2 and 3). However only 3 animalPrefabs[] (0, 1 and 2) are defined, as shown in the picture above.
Testing the script, however (printing Random.Range()'s outputs to the console), Random.Range() seems to be generating numbers from 0 to 2 only.
Is the documentation simply wrong? Otherwise, what's going on?


texts: Transparent parts of texture are opaque black instead

texts:
I render a sprite twice, one on top of the other.  The sprites have transparent parts, so I should be able to see the bottom sprite under the top sprite.  The transparent parts are black (the clear colour) and opaque instead though and the topmost sprite blocks the bottom sprite.

My fragment shader is trivial:

uniform sampler2D texture;
varying vec2 f_texcoord;
void main()
{
    gl_FragColor = texture2D(texture, f_texcoord);
}

I have glEnable(GL_BLEND) and glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) in my initialization code.  My texture comes from a PNG file that I load with libpng.  I'm sure to use GL_RGBA when initializing the texture with glTexImage2D (otherwise the sprites look like noise).

Edit: Here's a screenshot.


texts: How to deal with player inquiries (good, bad, and everything in between)?

texts:
I understand someone previously posted about dealing with bad suggestions from players. But I'd like to ask about dealing with inquiries in general.

When a game becomes popular, it's inevitable for you to receive heaps of emails from players (can be complaint about bugs, errors in purchases, etc). How do you usually handle these? Do you outsource these kind of things or do you try to answer the mails on your own during your free time? Or maybe create an online community like a forum?


texts:
Hi I've been making a game for the last few months and not sure what to do.

It's a 2d bike game and I want the rotation done with accelerometer, at the moment To test on computer I've set the rotation up as if left is hit transform.rotate to the left but because gravity my bike will not stay doing a wheelie.

Is there another way to do this can I just set up that the rotation of the bike is equal to the screen rotation? Or do I need the bike to stay in the air first and then when rotated right it goes right ect?

Really not sure and have been stuck on this for a month noob to unity too thanks


texts:
How would I go about detecting the corners of a texture when I use pixel collision detection? I read about corner collision with rectangles, but I am unsure how to adapt it to my situation.

Right now my map is tile based and I do rectangular collision until the player is intersecting with a blocked tile, then I switch to pixel collision.

The effect I would like to achieve is when the player hits the corner of an object to push him around the side so he doesn't just hit the edge and stop.

Any ideas?


texts: Libgdx. Converting Screen Click Coordinates into World Coordinates for 2D Game

texts: I'm using the InputHandler's touchdown method. It gives me my screenX and screenY. Is there a simple way to convert screenX and screenY to world coordinates? By my understanding, InputHandler returns the coordinates in relation to your screen.


texts: Creating a BufferedImage with several smaller images?

texts:
I am making a 2D tile based game. The tiles render fine from a spritesheet and a text file. However, I am using a for loop to draw the map to the screen. When it refreshes, it slows down the loop, and the bottom is black for a fraction of a second.

I was wondering if I could create a separate method to create a BufferedImage to hold the map, so I could render it continuously, and change it when needed.

Map Class:

package uk.co.madmonkeystudios.distortioner;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

public class Map {

    static BufferedImage sheet;

    public static void SetSpriteSheet() throws IOException{
        sheet = ImageIO.read(new File("res/grid.png"));
    }

    public static BufferedImage GetTile(int id) throws IOException{
        if(sheet == null){SetSpriteSheet();}

        int across = 24;

        BufferedImage tile = null;
        int x = 0;
        int y = 1;
        int w = 31;
        int h = 31;
        for(int done = 0;done<id;done++){

            x= done * w;
            x += id;
            if(done >= across){
                y += h;
                y++;
            }

        }
        tile = sheet.getSubimage(x, y, w, h);

        return tile;
    }

    public static void DrawMap(int id) throws IOException{

        Graphics2D g = (Graphics2D)Core.myself.getGraphics();

        g.clearRect(0,0,640,480);

        int[][] map = ReadMap(0);

        int xsize = map.length;
        int ysize = map[0].length;
        System.out.println("Map Read, size (" +xsize + "," +ysize+")");

        int x = Player.x;
        int y = Player.y;

        for(int loopy = 0;loopy<ysize;loopy++){
            for(int loop = 0;loop<xsize;loop++){
                g.drawImage(GetTile(map[loop][loopy]),loop * 32 + x, loopy * 32 +y + 25,32,32,null);
            }
            }
    }

    public static int[][] ReadMap(int id){
        int [][] map = null;
        try{
        @SuppressWarnings("resource")
        Scanner s = new Scanner(new File("res/maps/area"+id+".map"));
        int [][] map1 = new int[Integer.parseInt(s.next())][Integer.parseInt(s.next())];
        String current;

        int xsize = map1.length;
        int ysize = map1[0].length;

        for(int loopy = 0;loopy<ysize;loopy++){
        for(int loop = 0;loop<xsize;loop++){
            current = s.next();
            map1[loop][loopy] = Integer.parseInt(current);
        }
        }
        map = map1;
        }catch(NullPointerException ex70){
            System.err.println("Cannot read map in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't read map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        catch(FileNotFoundException ex71){
            System.err.println("Cannot find map in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't read map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        catch(ArrayIndexOutOfBoundsException ex72){
            System.err.println("Cannot add map to array in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't send map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        return map;
    }

}


texts: Clamp camera view angles relative to moving object

texts:
I have a camera attached to an entity that moves in a circular pattern around a fixed center position. I am attempting to clamp the rotation of the camera such that it can only look inward toward the center of the circle.

I have tried for some time to accomplish this but haven't had much luck.

Simply clamping the angles like this will not work:

rotation = Vector3.Clamp(rotation, new Vector3(-50.0f, rotationY, 40.0f), new Vector3(-20.0f, rotationY, 100.0f));

(the rotation angles are relative to world space, and not the local rotation of the entity)

I need to get a clamp value that is relative to the direction the entity is facing.

Is there any way I can accomplish this?

Update-

Adding the rotation of the entity to the camera rotation like in the following seems to work intermittently, but now it seems the camera starts stuttering at certain points around the circle.

Still stuck.

Vector3 clampMin = new Vector3(-50.0f, 0, 40.0f);
Vector3 clampMax = new Vector3(-20.0f, 0, 100.0f);

public void Update()
{
       // adding the users input
       rotation = camera.Rotation + (new Vector3(GetInputY(), 0, GetInputX()) * 4.0f);

       float clampX = ClampAngle(rotation.X, clampMin.X, clampMax.X);

       float clampZ = ClampAngle(rotation.Z,
                entity.Rotation.Z + clampMin.Z,
                entity.Rotation.Z + clampMax.Z);

       camera.Rotation = new Vector3(clampX, 0, clampZ);

}


texts: How can I load textures in Unity and keep them between scenes?

texts:
I have some textures that are used in multiple scenes and I want to keep them in memory to speed up load times between scenes.  I know about Resources.Load, but does that always keep it loaded?  If a texture is loaded with Resources.Load, will instantiating a prefab with that texture recognize that it's already loaded or will it load its own instance of the texture?

It would be better if it's a method that I can use in code so that I can make a loading screen and not freeze everyhing up.  I'm limited to an earlier version of Unity so I don't have access to LoadLevelAsyc.


texts: glTextImage2D with GL_UNSIGNED_BYTE giving weird results while with GL_FLOAT just works, driver bug?

texts:
Update: OK, not being able to see the textures loaded by FreeImage was just one of the common mistakes when using modern OpenGL. My texture loading code did not set GL_TEXTURE_WRAP_S/T and GL_TEXTURE_MIN/MAG_FILTER, and didn't have any mipmaps either: Textures "don't work" when I don't specify any texture parameters. Is this a driver bug or intended behavior?

May then the random colors I'm getting with the testing code be caused by the texture being too small? Maybe If I hardcode a 64x64 red square I will get same results in both cases. It is still weird that with float it works at 2x2 size.

I hit a wall trying to rewrite old sprite rendering code based on SDL to use modern OpenGL directly.

I'm loading images using FreeImage library and I already confirmed that the pixel data in memory is as expected. But at rendering I was getting no textures. So I harcoded a 2x2 image as a single dimensional array to pass to glTexImage2D and found something weird. When using float, result is as expected but when using char or uint8_t I get random colors.

Test code with floats:

        float pixels [] = {1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                           1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f};

        glGenTextures(1, &mRedSquareTex);
        glBindTexture(GL_TEXTURE_2D, mRedSquareTex);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels);

Test code with uint8_t:

        uint8_t pixels [] = {255, 0, 0, 255, 0, 0,
                             255, 0, 0, 255, 0, 0};

        glGenTextures(1, &mRedSquareTex);
        glBindTexture(GL_TEXTURE_2D, mRedSquareTex);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);

I think that if I walk pixel by pixel the data I'm loading using FreeImage and write them to a float array, I can finally see the textures loaded from disk. But It would be nice to just be able to use them as they are. As I'm not sure about the channels ordering of images loaded with FreeImage I'm avoiding the alpha channel for now, until I confirm the channels order, but in theory, as long as I avoid the alpha channel, I must be able to see the texture drawn, maybe with the wrong colors.

Shaders don't do anything special yet. The Vertex Shader just pass the textures coordinates as they are and the Fragment Shader just call texture().

I'm testing this in a machine with a NVidia GT 640, driver version 340.93, Ubuntu 14.04 64 bits.


texts: Skeletal animation with multiple animations running at the same time

texts:
I've spent a long time attempting to figure out how complex animations are done and wrote quite a few different skeletonish frameworks myself, but they've never really came out good enough to be properly used. So maybe someone here knows how complex things that can have lots of different animations are animated. I know that you can combine different animations to create one larger thing, but that takes A LOT of time and can't be organised properly, or even designed properly if you are attempting to design complex characters.

So I'm wondering whether anyone knows about known techniques for this, I'm willing to write my own implementation of it (Using a quite unpopular language, usually can't find libraries or anything for it). Or a software that you can write an implementation of your own in your own language.

TL;DR: Looking for software / animation theory that can handle applying multiple different animations of the same character.

Spine2D and spriter aren't what I'm looking for.


texts: How can I implement smooth rotation from one direction to another?

texts:
I'm having a problem with animating rotations with 1Matrix.CreateRotationY() with my basic 3D game. Based on where you click the mouse, I want the 3D object to rotate to that direction and then move.

I am using this to determine the target direction:

float rot = (float)(Math.Atan2(X, Z));

It gives me the correct value, but I am not sure how to handle the rotation animation from current direction to new direction. I've tried a few things, but to no avail.

Do you guys know of any good ways of solving this issue?


texts: How should I manage Roguelike levels/maps in JavaScript?

texts:
I am developing a Roguelike in JavaScript using ROT.js. I'd like to keep with traditional gameplay (permadeath, randomly generated dungeons/mobs/items), but I want to have a statically defined overworld with randomly generated dungeons beneath.

Currently, I use the TILED map editor to create my overworld map and export it to JSON/JS format and import/parse the map into my game. For randomly generated dungeons, I use ROT.js's built in dungeon generator tool to create dungeons that are in the same JSON/JS format that the TILED maps are in.

The issue I am facing is finding an efficient way to store these maps and levels once they are generated, alongside the overworld. Right now, I just throw the generated maps into a JavaScript object indexed by the name of the map. Here's an example of how I do this currently:

levels = {};
// map class parses TILED map json and creates actors based on ascii
let map = new Map(TiledMaps["overworld"]);
levels["overworld"] = map;
let dungeon = new Map(randomMap(...)); // random map generates tiled map
levels["dungeon1"] = dungeon;
// to switch levels, just set the current game map
Game.map = levels["dungeon1"];

Is this a good approach? I would like to consider the possibility of having different types of dungeons. So, in the overworld, you might visit different sections of the world and those have different dungeons. Something like Link to the Past perhaps? Any advice?


texts: FPS reticule image scaling with resolution problem

texts:
I am running into a problem when I set the resolution of my screen and the objects in the HUD. When an increase of resolution happens the reticule image becomes bigger, when I want it to stay the same. Anyone got any tips?

Thanks in advice.


texts: Orbital mechanics: orbit as a function of time. Universal variable formulation?

texts:
I am trying to model a two dimensional orbit for a two body Kepler problem but have gotten stuck when introducing the time variable.

For a satellite with known semi major axis (a), eccentricity (e), and true anomaly (theta), I have:

r = a*(1-e**2)/(1+e*cos(theta))

How can I calculate theta as a function of time using the Wiki suggested  Universal variable formulation method?  I have no idea how to implement (am using Python but any algorithm advice much appreciated!)

Alternatively, how do I calculate r as a function of time?

Note: All other orbital elements and masses are available. Also I am trying to come up with a general solution for elliptical, hyperbolic and parabolic orbits.

Cheers!


texts:
What is the best option if I want to show a remote webpage inside a UI Panel in Unity ?

I want to target android and iOs platform.

I had uniWebView in mind but that thing is more like an overlay I guess, or can it be kept in bound of the panel (the canvas which holds the panel is using world co-ordinate) ?


texts: I'm learning blender and am wondering what size(blender units) I should be making my characters and maps. should i consider 1 blender unit as 1 inch, foot, meter or does it not not matter?


texts: Are there games already including detailed psychological/social modeling?

texts:
I have this project that have been running in my head for some time, and was surprised to realized I have never seen it in an existing video game. So I thought I might be wrong.

Most of current video games use basic social modeling, for example:

Actor1 goes from A to B, then back to 1. Repeat
Actors walk around limited area. When 2 Actors meet, they interact for 10s, then go back to walking
Actors have complex patterns, e.g. Oblivion (eat lunch under this place at 1am, except if raining, goes to this city on Sundays, etc)

My point is, it is currently mainly based on scripts. To use a graphical equivalent, it is as when physical interactions were limited/scripted, compared to current games having a detailed physics engine allowing realistic and unscripted interactions (think "Link to the Past" arrows compared to "Skyrim" arrows)

The main difference would be that there are detailed and verified models of physical behavior, gravity, etc, where as psychology/social tend to be more "fuzzy". However, there are psychological models out there, some of them widely accepted and verified, and not that difficult to implement (for example, distance between people during a social interaction, group theory, and all that). I believe that it would make a game more realistic, which is often a good point.

An example would be the "pretty rich girl / beggar" situation. In most games, either they interact as soon as they are less than 5ft from each other, and in the same way as two "equal" characters would interact (both are doing gestures while talking, they are talking about the weather, looking each other in the eyes, etc), or they are scripted not to talk to it to each other. In both cases, it would be different than what you would expect in real life.

So, (finally) the question: Are there games out there that have implemented and modeled real psychological/social models? Or even tried, and realized it was not working?


texts: Should camera rotation be framerate independent?

texts:
I currently have my own custom first person controller, and the code to rotate the camera and controller based on the mouse position deltas looks like this:

public void ApplyRotation()
{
    this.transform.transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X") * this.Sensitivity * Time.deltaTime, 0));
    this._VerticalRotation += Input.GetAxis("Mouse Y") * this.Sensitivity * Time.deltaTime;
    this._VerticalRotation = Mathf.Clamp(this._VerticalRotation, -85, 85);
    Camera.main.transform.eulerAngles = new Vector3(
        -this._VerticalRotation,
        Camera.main.transform.eulerAngles.y, Camera.main.transform.eulerAngles.z
    );
}

Right now, I'm using Time.deltaTime in the rotation code to keep the rotations framerate dependent, but I'm not sure if I should be doing this when I'm dealing with the mouse. Should I keep this framerate dependent, or should it be framerate independent?


texts:
I want to know to code structure of a game that has different levels to choose from on the main screen. More precisely, I want to know how does the main loop hands off the rendering to another loop that exist in the level code.

I could think of a solution but I would like to know how this is done by game developers.

Solution:

// Level.cpp
void Level::LevelLoop() {
    while(LevelNotDone){
        handleInput();
        update();
        render();
    }
}

// Main.cpp
void MainLoop() {
    while(GameNotDone){
        handleInput();

        if (Condition to start level)
            level.LevelLoop();

        // wait until level loop exits

        update();
        render();
    }
}


texts:
I apologize if this has been answered already. I've looked around here, and read a few blog posts, but none seem to fully answer my question.

I am writing an Entity Component System.

Entity is a store for Components, and is the central GameObject.
Component is just a POD struct that describes some attribute (Health, Mana, etc.)
System dictates the laws of the game world. Systems describe how an Entity will behave based on the Components that entity has, and the data stored within the Component. Additionally, a System can interact with other Systems using Events.

A pretty straight-forward and common approach. Now, the issue I am having is when an Event should interact with an Entity. For example, a DieOnCollision event for some Entities, or a HealOnUse event for others.

At first, I thought about just making a bunch of Systems for every type of event. An Entity would subscribe to these Systems, just like other Systems, except their Update function would do nothing. Instead, they only operated once per frame when passed an Event from the EventQueue.

I don't like this approach, because it is putting the System in charge of specific Entities, rather than operating on a collection of Entities.

Another approach I thought of was just creating a Component for each event, each of which holds a function pointer. When an event happens, such as ExplosionEvent, a list of entities in the area is given to the EventHandler, which then checks for the OnExplosionEvent component and calls the corresponding function (or maybe queues it up so all the functions can be processed in order).

I'm not too fond of this approach either, because it puts behavior into a component and it puts the EventHandler in charge of telling the Entities. Of course, I could probably just have the EventHandler pass the Event to GameWorld which then passes it to the Entities who have the needed components, but it still puts behavior into a component, which I want to avoid.

One last idea that just came to me would be to give the Entity a map of events it can listen for, something like std::map<EventID, FunctionPointer>. The entities could then be notified of Events during event handling, and their functions could be queued up. I do like this approach, but I am curious if there are any other suggested ways to handle Events pertaining to an Entity rather than a System.


texts: How to render a single texture across multiple tiles? (Unity2D)

texts:
I'm making a top-down style game in Unity 5 (2D). The floor is made up of many tiles (which are each game objects) of different types, eg sand and dirt.

I want to render a single texture over all of a single type of tile. So if I had a large area of sand, a single texture would be displayed for all of it. However, if there was a small area of dirt within that sand, that would need its own texture as well. These areas wouldn't necessarily be square either.

I've seen this used in games such as RimWorld, but I have no idea how to accomplish it. Any ideas?

Edit: Added picture of what I am attempting. This is a screenshot from RimWorld. As you can see, the sand is made up of hundreds of tiles, but has only one texture over it.

This is all I have managed so far:


texts: How can I customize Unity editor controls?

texts:
I have been using blender for quite some time so I know pretty much how it works, and I have just recently started using Unity.

I find the unity UI to be very confusing and hard to use, and I was wondering if there was a way to change the controls to be more blender-like. what I mean is, "shift + scroll" to pan, or just "scroll" to orbit.


texts: Random movement of game Object staying in a circle

texts:
I want to write a script which makes several objects move in a random direction but within a range around another game object. If the parent object moves then that range should also be changed accordingly.

How can I achieve such behavior?

Here is a video which demonstrates the behavior I am looking for.

It looks approximately like this:

   void Update ()
   {
        time += Time.deltaTime;

        if (time > 1.0f)
        {
            CalculateRandomRotation ();
            time = 0f;
        }

        FindSpiritsBound ();

    }

    void CalculateRandomRotation()
    {
        x       = Random.Range(-velocityMax, velocityMax);
        z       = Random.Range(-velocityMax, velocityMax);
        angulo  = Mathf.Atan2(x, z) * (180 / 3.141592f);
        time    = 0.0f;
        transform.localRotation = Quaternion.Euler(0, angulo, 0);
    }

    void FindSpiritsBound()
    {
        if (Vector3.Distance (parentObj.transform.position, gameObject.transform.position) < 3f)
        {
            gameObject.transform.localPosition += gameObject.transform.forward * 4f * Time.deltaTime;
        }
       else
        {
         transform.position = Vector3.MoveTowards(transform.position, parentObj.transform.position, 2.0f);
        }
    }

Here is my script which doesn't seem to work properly as on moving the main character, spirits are going wayward.


texts:
I'm working on a build mode but the thing of it is the player is able to deform meshes. Part of my build system includes having "snap" points thus I need to be able to find the face and recenter the snap point on deformed meshes.

So, how do I find the face of an object and the center of said face? Also how would I find the center?

To clarify: The end goal is to keep the snap point positioned properly with the face that has been deformed/manipulated.


texts: Prevent near-plane culling in vertex shader

texts:
I am rendering a non-sphere light mesh and the standard question is how to cull: cull front faces and you loose Z-Testing benefits, cull back and you get into situations where camera is not rendering parts of the mesh due to near-plane clipping.

I thought myself smart, set culling to back and wrote this code in the vertex shader:

o.position = mul(ViewProj, i.worldPos);
if (o.position.z < 0 && o.position.w > 0)
   o.position.z *= -1;

This did nothing :). I wanted to ask if I am even thinking in the right direction (whether it is even possible to prevent camera's near-plane culling in the vertex shader)?


texts: What is a good strategy to recruit test players for a chess app?

texts:
We developed a chess app for iMessage and we would like to have people try it out and tell us their opinions.

Do you know a good strategy to give away free promo codes for the pro version of our new game?


texts: Pathfinding Search for Path of Specific Length

texts:
I am creating a roguelike.  This question applies to random map generation.

First, I generate areas using a BSP algorithm, where I randomly divide the map into areas.
Then, I generate a graph of the areas so that I can use search algorithms to generate paths through the map.
It is easy to find the shortest path between two areas, but I would like to find a path with a specific number of steps(or path cost).

So, my question is:  What is an algorithm that I can use to find a path that has a specific cost or cost range?

An Example of why I think this is useful:
Say that I randomly choose two areas(start and end for example).  These area might be next to each other, they might be on the opposite sides of the map.  I want to force the player to travel through a minimum number of areas before reaching the end, let's say 5.  I should be able to be like:

path = startArea.findPathMinimumCost(endArea,5);

And it will return a path of cost 5, or the shortest path, whichever has the greater cost.

Thank you.


texts: How to Calculate the Contact Point between Ray and Plane

texts: Is there any quick way to find the intersection point between Plane and Ray?


texts: Helicopter controller, spherical world with faux gravity

texts:
I followed this tutorial to create a planet with faux gravity that attracts objects.

Further I'm trying to create a helicopter-like controller that could move vertically and horizontally and that when the player presses control buttons this would compensate the faux gravity applied with AddForce to Rigidbody and the helicopter could fly. I implemented that in a way that when player presses buttons faux gravity with AddForce is not applied, but still the control feels very awkward.

What would be the best way to compensate the faux gravity to move the helicopter?

Edit: I only need it to move in XY plane (so only up/down/left/right). The camera looks on helicopter from its right side. The attractor script works in 3 axis and this is ok for now.

Player controller (assigned to the helicopter):

public class PlayerController : MonoBehaviour {
    public float moveSpeed = 15;

    private Rigidbody rb;

    private Vector3 moveDir;
    private float h;
    private float v;

    void Awake() {
        rb = GetComponent<Rigidbody>();

        if(!rb) throw new Exception("Game Object must have Rigidbody!");
    }

    void Update () {
        GetControls();
        moveDir = new Vector3(h, v, 0).normalized;
    }

    void GetControls() {
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");
    }

    void FixedUpdate() {
        rb.MovePosition(rb.position + transform.TransformDirection(moveDir) * moveSpeed * Time.deltaTime);
    }
}

Faux Gravity Attractor (assigned to the planet):

public class FauxGravityAttractor : MonoBehaviour {
    public float gravity = -10;

    public void Attract(Transform body) {
        Vector3 gravityUp = (body.position - transform.position).normalized;

        Vector3 bodyUp = body.up;

        Rigidbody bodyRb = body.GetComponent<Rigidbody>();

        bodyRb.AddForce(gravityUp * gravity);

        Quaternion targetRotation = Quaternion.FromToRotation(bodyUp, gravityUp) * body.rotation;
        body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 50 * Time.deltaTime);
    }
}

Faux Gravity Body (assigned to the helicopter):

public class FauxGravityBody : MonoBehaviour {
    [SerializeField]
    float gravity = -10;

    public FauxGravityAttractor attractor;
    private Transform myTransform;

    void Start () {
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.constraints = RigidbodyConstraints.FreezeRotation;
        rb.useGravity = false;
        myTransform = transform;
    }

    void Update () {
        attractor.Attract(myTransform);
    }
}


texts: Game (Physics) work in Unity Editor/Remote but won't on Android?

texts:
I have a script attached to a car game object that allows the player to tap the screen and then accelerate, the game object has a RB2D and collider set to it , it works fine in Unity Remote , but when I download the APK , as soon as I tap the screen , collisions go completely bezerk and the car just starts ignoring collisions , what's going on? As I need this to work to complete my game , as the player can move side to side with the accelerometer but I also want them to move forward when they touch the screen. Also , my game is 2D. Plus , since then , when the car ( my object) collides with anything else in the scene , it ignores it ( the obstacles just have Box Colliders on them). I had to freeze rotation so it could stop spinning out when it hit soemthing , now it just won't recognize collision at all. What's going on?
The code I think is causing the error starts at line 32. I have obstacles the player has to dodge and they all have box colliders and an appropiate script attached to them as well ( so when they collide with my player , it destroys it)

I've figured it out , Collision works when I first start the game , but when the player dies and I press "Replay" , it goes crazy. Here's the script that controls the enemy cars spawning , what the hell do I do to fix this?

 Code (CSharp):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCar : MonoBehaviour {
public float speed ;
public float acceleration = 0.5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
    speed += Time.deltaTime * acceleration;
    transform.Translate(new Vector3(0, 1, 0) * speed * Time.deltaTime);

}
void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Coin")
    {
        Destroy(col.gameObject);
    }
}
}

I've done everything in the book trying to solve this , re-install unity , add different colliders etc. What's weirder is that it is FLAWLESS in Unity Remote and the Editor , these issues only arise when I test out the apk.

Here's how my game usually looks when the collisions work.

Now when it collides with a car ( on android) , it just ignores it and is slightly pushed back.

Help me!

Here is my script attached to enemy cars ( the cars that should destroy the player on Collision)

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

public class EnemyCar : MonoBehaviour {
    public float speed ;
    public float acceleration = 0.5f;
 // Use this for initialization
 void Start () {

    }

    // Update is called once per frame
    void Update () {
        speed += Time.deltaTime * acceleration;

        transform.Translate(new Vector3(0, 1, 0) * speed * Time.deltaTime);

 }
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Coin")
        {
            Destroy(col.gameObject);
        }
    }
}

Also here is the inspector view of my Player Car

Here is the inspector view of an enemy car ( they all have the same things)


texts: How to get position of CCSprite added to CCParallaxNode?

texts:
I have a CCparallaxNodeExtras that scrolls infinite (following the space game tutorial). I added as a child a CCSprite made of other CCSprite, like this:

_backgroundNode = CCParallaxNodeExtras::node();
this->addChild(_backgroundNode,-2);

    float acum = 0.0;
    back1 = CCSprite::create();
    for(int i = 0; i < num_repeats; ++i) {
        CCSprite *back = CCSprite::createWithSpriteFrameName("rock.png");
        back->setPosition(ccp(acum, 0));
        back1->addChild(back);
        acum+= back->getContentSize().width+150.0;
    }

    _backgroundNode->addChild(back1,  1 , ccp(0.1,0.1), ccp(0, winSize.height * 0.64));

now in my update I have this:

CCPoint backgroundScrollVert = ccp(-1024, 0);
_backgroundNode->setPosition(ccpAdd(_backgroundNode->getPosition(), ccpMult(backgroundScrollVert, dt)));

perfect, the background moves and disappears (that is what I want for now) but I need to get the collision between the sprites on that background and a fixed sprite as a child of the main node.

The problem is that whenever I try to get the collision by the simple way (intersecting the bounding boxes) it doesn't work, so I tried to just get the position of the sprites and all I get is the position fixed in the CCSprite (back1) composed by the sprites (back).

Now, is there a possible way to get the position of any individual sprite located in that parallax node? If i try something like:

CCSprite *tempsprite = (CCSprite*)_backgroundNode->getChildren()->objectAtIndex(0);
printf("%f\n", tempsprite->getChildren()->objectAtIndex(0)->getPositionX());

it prints always the same value, it is like the position is not being affected by the transformation of the parent in the background node... so, how do I get it correctly? how do I get the position relative to screen and not to the parent?


texts:
I don't know if this is the right question for Stackexchange because it is based on opinion, so excuse me if it's not.

I'm currently developing a mobile leisure game in a cartoon style where players build and expand their kingdom, in a medieval setting. Users can be part of a group to help each other, trade goods, communicate together,  and support each other when attacked. The game is NOT a fight game only. Developing and maintaining your city and the citizens is an important aspect, socializing with other players is key, and the target audience are both men and women.

I'm really confused how I should name such groups where you can be part of. Clans, guilds, teams, groups or factions: all of them are possible. When should I use which name? And what would fit my situation the best? It's really important to let users feel they are part of a group. Not just a fighting group, but a group both men and women feel attracted to. A fraction for example would not be the best I think.

I realize this heavily depends on opinions. Buy are there any sources that could help me? What do you feel attracted to? What fits my situation the best?


texts: Making an efficient collision detection system

texts:
I'm very new to game development (just started 3 months ago) and I'm learning through creating a game engine. It's located here. In terms of collision, I know only brute-force detection, in which case, the game slows down if there are a number of objects. So my question is How should I program the collisions?

I want them to happen automatically for every object and call the object's collision(GObject other) method on each collision.

Are there any new algorithms which can make this fast?
If so, can anybody shed some light on this topic?


texts: How do I determine the draw order in an isometric view flash game?

texts:
This is for a flash game, with isometric view. I need to know how to sort object so that there is no need for z-buffer checking when drawing. This might seem easy but there is another restriction, a scene can have 10,000+ objects so the algorithm needs to be run in less than O(n^2). All objects are rectangular boxes, and there are 3-4 objects moving in the scene. What's the best way to do this?

UPDATE

in each tile there is only object (I mean objects can not stack on top of each other). and we access to both map of Objects and Objects have their own position.

UPDATE2

see these figures:

in first one first blue object should be drawn then green then red. while in second one you have to draw them in reverse order. you need to draw red first and then green and finally blue object. as you can see there is no difference in position of blue and red objects ,they both have different distance from camera and so on. but because of their relative position to green box, you need to change their draw order between two images. that's what makes this problem a mess.

side-note: since all objects are rectangular prism, it's mathematically provable that there is at-least one draw order to satisfy problem needs.


texts: How to get the result of random item with different possibility?

texts:
I'm wondering if anyone can guide me with following problem...
Each fruit has different chance to be called out.

Apple - 80%
Orange - 10%
Banana - 10%

Each time a user click on the random image, only 1 fruit will come out with above weight.
I have no idea how I can calcuate to get that result. Pseudo code example is fine for me.


texts:
Dears,
I am building a flight simulator game with third person camera. I facing a problem that when I go high with the plane, objects, land and farms didn't look very far.
I tried to change the field of view for the camera, but I face a stretching in the drawn objects.
My questions is:

Am I right to change the FOV for the camera? If yes, how to change the FOV without stretching.
If the previous question is no, How to give the feel for the land, terrains and farms that they look very far when I go up in the sky?

Any idea, tutorial or documentation is highly appreciated.
Thanks.


texts: Why do games usually don't allow arbitrary window resize?

texts: Why do games usually only allow some specific resolutions, instead of allowing arbitrary window resizing? Are there any technical difficulties for arbitrary window resizing?


texts:
I have designed an entity system for an FPS. It basically works like this:

We have a "world"-object, called GameWorld. This holds an array of GameObject, as well as an array of ComponentManager.

GameObject holds an array of Component. It also provides an event mechanism which is really simple. Components themselves may send an event to the entity, which is broadcasted to all the components.

Component is basically something that gives a GameObject certain properties, and since GameObject is actually just a container of them, everything that has to do with a game object happens in the Components. Examples include ViewComponent, PhysicsComponent and LogicComponent. If communication between them is needed, that can be done through the use of events.

ComponentManager just an interface just like Component, and for each Component class, there should generally be one ComponentManager class. These component managers are responsible for creating the components and initializing them with properties read from something like an XML-file.

ComponentManager also takes care of mass updates of components, like the PhysicsComponent where I will be using an external library (which does everything in the world at once).

For configurability, I will be using a factory for the entities which will read either an XML-file or a script, create the components specified in the file (which also adds a reference to it in the right component manager for mass updates), and then inject them into a GameObject object.

Now comes my problem: I am going to try to use this for multiplayer games. I have no idea how to approach this.

Firstly: What entities should the clients have from the beginning? I should start with explaining how a single-player engine would determine what entities to create.

In the level editor you can create "brushes" and "entities". Brushes are for things like walls, floors and ceilings, basically simple shapes. Entities are the GameObject I have told you about. When creating entities in the level editor, you can specify properties for each of it's components. These properties are passed directly to something like a constructor in the entity's script.

When you save the level for the engine to load, it is decomposed into a list of entities and their associated properties. The brushes are converted into a "worldspawn" entity.

When you load that level, it just instanciates all the entities. Sounds simple, eh?

Now, for networking the entities I run into numerous problems. First, what entities should exist on the client from the beginning? Assuming that both the server and client has the level file, the client could might as well instanciate all the entities in the level, even if they are there just for the purposes of game rules on the server.

Another possibility is that the client instanciates an entity as soon as the server sends information about it, and that means that the client will only have entities that it needs.

Another issue is how to send the information. I think the server could use delta-compression, meaning that it only sends new information when something changes, rather than sending a snapshot to the client at every frame. Though that means that the server must keep track of what each client knows at the moment.

And finally, how should networking be injected into the engine? I'm thinking a component, NetworkComponent, which is injected into every entity that is supposed to be networked. But how should the network component know what variables to network, and how to access those, and finally how the corresponding network component on the client should know how to change the networked variables?

I'm having huge trouble approaching this. I would really appreciate if you helped me on the way. I'm open to tips on how to improve the component system design too, so don't be afraid of suggesting that.


texts:
I am having trouble installing UE4 on my computer. I keep getting Error 2738 as I start the installation and can't find a fix. Even Microsoft Fix It 50842 won't work.

I've attempted to re-download installer, reboot, use a flash drive. Still the same error.

Anybody else been having this issue? If so how did you fix it?


texts: I don't understand code that builds 3D sphere

texts:
I'm trying to learn some lwjgl and opengl, and I was trying to make a 3d sphere etc, I found a code to do that, but I don't 100% understand the code and the math behind it and would like to get some deeper explanation about it.

This is my draw sphere method:

public void drawSphere(float radius) {
    final float PI = 3.141592f;
    float x, y, z, alpha, beta;
    int gradation = 100;
    for (alpha = 0.0f; alpha < Math.PI; alpha += PI / gradation) {
        glBegin(GL_TRIANGLE_STRIP);
        for (beta = 0.0f; beta < 2.01f * Math.PI; beta += PI / gradation) {
            x = (float) (radius * Math.cos(beta) * Math.sin(alpha));
            y = (float) (radius * Math.sin(beta) * Math.sin(alpha));
            z = (float) (radius * Math.cos(alpha));
            glTexCoord2f(beta / (2.0f * PI), alpha / PI);
            glVertex3f(x, y, z);
            x = (float) (radius * Math.cos(beta) * Math.sin(alpha + PI / gradation));
            y = (float) (radius * Math.sin(beta) * Math.sin(alpha + PI / gradation));
            z = (float) (radius * Math.cos(alpha + PI / gradation));
            glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);
            glVertex3f(x, y, z);
        }
        glEnd();
    }
}

I understand the general idea of this, and I understand how the x, y, z are calculated, but what I don't understand is the 2 nested loops aka:

for (alpha = 0.0f; alpha < Math.PI; alpha += PI / gradation)

and

for (beta = 0.0f; beta < 2.01f * Math.PI; beta += PI / gradation)

One more thing, is the glTexCoord2f that I don't quite understand the math behind it, so an explanation about this would be really nice as well for:

glTexCoord2f(beta / (2.0f * PI), alpha / PI);

and

glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);


texts: Coroutine problem, I don't know what's happening

texts:
Calling function.

 private const int deathHangTime = 2;
 private void Die()
    {
          Debug.Log("1 " + Time.time);
          StartCoroutine(DelayForTime(deathHangTime));
          Debug.Log("4 " + Time.time);
    }

  Coroutine

IEnumerator DelayForTime(float time)
{
     Debug.Log("2 " + Time.time);
     yield return new WaitForSeconds(time);
     Debug.Log("3 " + Time.time);
}

Why doesn't it wait for 2 seconds?
Why doesn't it print the 3rd Debug line?


texts: Sprite and Physics components or sub-components?

texts:
I'm taking my first dive into creating a very simple entity framework. The key concepts (classes) are:

Entity (has 0+ components, can return components by type)
SpriteEntity (everything you need to draw on screen, including lighting info)
PhysicsEntity (velocity, acceleration, collision detection)

I started out with physics notions in my sprite component, and then later removed them to a sub-component. The separation of concerns makes sense; a sprite is enough information to draw anything (X, Y, width, height, lighting, etc.) and physics piggybacks (uses the parent sprite to get X/Y/W/H) while adding physics notions of velocity and collisions.

The problem is that I would like collisions to be on an entity level -- meaning "no matter what your representation is (be it sprites, text, or something else), collide against this entity." So I refactored and redirected collision handling from entities to sprite.physics, while mapping and returning the right entity on physics collisions.

The problem is that writing code like this.GetComponent<SpriteComponent>().physics is a violation of abstraction. Which made me think (this is the TLDR): should I keep physics as a separate component from sprites, or a sub-component, or something else? How should I share data and separate concerns?


texts: Increasing resources overtime for a browser-based game

texts:
I've been interested in developing a browser game ala OGame or Ikariam etc. Basically, a menu is displayed with your resources and, overtime, they increase depending on how advanced are you in the game.

Now then, the "resources" information for all players is stored in a MySQL database.

I've considered two methods to keep track of a player's resources:

Update database every second

Every second, something like

UPDATE `Players` SET `Gold` = `Gold` + `GoldProduction`

This is one option. However, performing a query every second for a potentially large table of players is not exactly appealing - but I might be underestimating my server. Am I?

Calculate it when needed

Since you get gold every second, technically the amount of gold any player has should be

(currentTime - creationTime) * goldProduction

What if the player spends gold? Well, gold spending should affect a variable goldModifications:

goldModifications + ((currentTime - creationTime) * goldProduction)

So if you spend 100 gold, goldModifications would be -100.

But wait. Players can upgrade their gold production. Hence, goldProduction isn't constant and this formula is flawed...

... Maybe when you upgrade your gold production, goldModifications will be modified by your current amount of gold (so if you had 1500, we would do goldModifications += 1500), then creationTime will be overwritten to the current time.

So I have two methods. One is incredibly simple (just update the database), but I am unsure if it is too much overhead or not. The other is very complex as there could be any number of factors affecting gold production, but certainly requires less processing power.

What should I do? What do those popular games actually do?


texts: Drawing flaming letters in 3D with OpenGL ES 2.0

texts:
I am a bit confused about how to achieve this.  What I want is to "draw with flames". I have achieved this with textures successfully, but now my concern is about doing this with particles to achieve the flaming effect. Am I supposed to create a path along which I should add many particle emitters that will be emitting flame particles? I understand the concept for 2D, but for 3D are the particles always supposed to be facing the user?

Something else I'm worried about is the performance hit that will occur by having that many particle emitters, because there can be many letters and drawings at the same time, and each of these elements will have many particle emitters.

Update 1:

A more detailed explanation:

I have a path of points, which is my model. Imagine a dotted letter "S" for example. I want make the "S" be on fire. The "S" is just an example it can be a circle, triangle, a line, pretty much any path described by my set of points.

For achieving this fire effect I thought about using particles. So I am using a program called "Particle Designer" to create a fire style particle emitter. This emitter looks perfect on 2D on the iphone screen dimensions. So then I thought that I could probably draw an S or any other figure if i place many particle emitters next to each other following the path described.

To move from the 2D version to the 3D version I thought about, scaling the emitter (with a scale matrix multiplication in its model matrix) and then moving it to a point in my 3D world. I did this and it works. So now I have 1 particle emitter in the 3D world.

My question is, is this how you would achieve a flaming letter? Is this too inefficient if i expect to have many flaming paths on my world? Am i supposed to rotate the particle's quad so that its always looking at the user? (the last one is because i noticed that if u look at it from the side the particles start to flatten out)

Update 2:

I tested this, by having multiple particle emitters and altho they look reasonably well the more particles i have the worst the FPS get. A common scenario will be having at lest around 50 different lines/letters at the same time.

Currently the particle emitter is on the cpu. It calculates the position of each of the particle's vertices and feeds the new vertices to the gpu. This works well for a few emitters, but not for enough to have "flaming" letters all around.

I was considering about moving the calculations performed by the particle emitter to the GPU in a shader but this seems a bit complicated since each particle has its own state and is modified with a time delta. In the CPU it is simply an object that changes its value with the previous value as reference, but the GPU shader is just run once per draw call isn't it?


texts:
I've been working on an simple RPG game and I'm having troubles figuring out how my graphics should look.

I'm wondering if any of you could give some advice on how they are/could be more pleasing to the eye.

Here is a couple of screen shots of the game itself:

Any suggetions/comments!

Thanks!

Sorry, I'm unable to post more pictures, because of my repution :(

Edit:
 After some working on the look of the game here is where I got to...


texts: Integrating a leader board with FaceBook?

texts: Think like how Bejeweled 2 does its Blitz mode where it connects to Facebook, pulls your friends names and their top scores for the week.  Are there any libraries, etc. that already help facilitate this process?  I would rather not re-invent the wheel if necessary.


texts: Find two points in a point cloud with the maximum distance?

texts:
What is the least computationally complex way to find two points such that the distance between them is greater or equal to any other pair.

Remember hearing something about how you could find such a pair by randomly picking a point r, finding the point furthest away fa and then finding the most distant point from it, md. The diameter is then the distance between fa and md (i.e norm(fa - md)).
Is this correct? Can you prove or disprove it? What is the correct way if this is incorrect?


texts: Implementing a 2D destructible landscape (like Worms)

texts: What steps would be involved in constructing a destructible 2D landscape, like in Worms? Ideally, What are some ways that this process could be made efficient as possible?


texts: Attach simple, portable 2D graphics for a c++ game

texts:
I have a game written in C++ (using STL and c++11 extensively).

I would like to do the following things:

Attach graphics to this game -> Think chessboard of some kind. I just need some pictures and simple status bars, no movement necessary, even though it would be nice I guess. It's a turn based game.
Port the game across Windows / Android / iOS

So, all in all, I need a tool that would provide a portable, simple, 2D graphical interface. A tool that would allow me to "bind" my c++ code to portable graphical representation.

How would I go about making this idea come true?


texts: Why this simple SFML app produce such high CPU usage?

texts:
I written the following SFML.NET app.
It  draw a single 128x128 sprite on the screen.

RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML window");
window.SetVerticalSyncEnabled(true);

Texture texture = new Texture("test.jpg");
Sprite sprite = new Sprite(texture);

// Start the game loop
while (window.IsOpen())
{
    window.DispatchEvents();
    window.Clear();
    window.Draw(sprite);
    window.Display();
}

Since VSync is enabled, the number of FPS is capped to 60. I expect the program to use very little CPU, but under task manager it show me that is use about 50%  (two cores fully actually). Also it seems it use about 30% kernel time and the rest is user time.

The exact same application in SDL (just drawing a single sprite) use about 0% (regardless SDL_RENDERER_ACCELERATED is used or not).

EDIT : surprisingly, if I let the app run for a given amount of time (let's say 10-20 seconds, the CPU usage fall down to 0%). I manage to repeat this several times. That is really strange.


texts: How would I create Dynamic LOD with Quad Trees

texts:
I would like to be able to create something like the following http://www.youtube.com/watch?v=LxZhWrSmrOY&feature=player_embedded how would I create something like it? I understand I will have to use quad trees and cube to sphere projection, but I don't even know how I will structure the program or even create the sphere.

I would like to know how I would structure the program (an interface of the members I would need particularly in the quad-tree class, and the class which holds the quad-treesm etc)
How do I make it so dynamic like that?
How would I create the quad tree structure and how would it work (and interact with other objects)?
Any other information/things you can provide me with :3
How to create the sphere, etc.

Eventually I would like to be able to create something like this: http://www.youtube.com/watch?v=rL8zDgTlXso but I guess creating this (the first thing mentioned) is a part of it?

Anything would be appreciated.

Edit:

I found the source code for the first project at https://github.com/unconed/NFSpace the only problem is, is that it is in C++ and Orge, and I don't really understand any of it, help please! :)


texts: May I put a ClickListener to the Stage or better if every Actor/Group has its own?

texts:
On the web it's almost always better to have a single click event listener at the top of a hierarchy. For example in a tabular data representation the <table> element would listen for all its child elements instead of each <tr> or <td> having their own listeners, since the event knows its originating element anyway.

Instinctively I'd do the same in LibGDX Scene2D and put my ClickListener to the Stage instead of the Actors or Groups.

So far I haven't seen anything which suggests I'm doing it wrong, but as I'm new to LibGDX I thought I'd ask.

Clarification

I'm a bit worried about possible memory management issues, similarly to when certain Disposables aren't properly disposed, or when I forget to use pooling on objects which are constantly reused.


texts: How can I run a Node server on the player's machine?

texts: I'm making a game with Unity. The game's multiplayer server runs on Node, but it's only run on my own machine. How do I bundle Node to my game's installer to install it on my player's machine?


texts:
I am building a game in jMonkey (Java) and I have so far only used default quest text. But now I need to start populating a lot of quests with text. My design requires A LOT of quests texts.

What is the best way to build a database of quest texts in jMonkey? I don't have a lot of real experience with databases. Is there a database that integrates well with jMonkey?

Here are the ideal properties I want in my database, in order of priority:

Reasonably light learning curve
Easy portability (in Java) to Windows, Linux, and Mac OSX
Good interface with Java
Good interface with jMonkey
The ability to add properties to the quests: ID, level, gender, quest chain ID, etc.

Or am I wrong in thinking I need to use some giant monster like SQL? I haven't been able to find much information on this, so are people using some non-database methods for storing things like quest text in jMonkey?


texts: How to make an object in box2d have constant velocity even after collision?

texts:
I have iOS game where I have a bouncing character. Everything is being handled by box2d. The problem is when the character hits a wall of another character it's velocity changes, but I don't want this. I need the velocity to stay constant even after collisions.

I was thinking the only way to do this was to keep setting the velocity after each collision unless there's another way to do this that I'm not aware of?


texts:
I'm rendering an aggregation of value into an R32F format texture, using alpha blending to accomplish the sum operation.

R32F alpha blending is not supported on all hardware. What kind of fallback options do I have for accomplishing the addition in when the hardware doesn't support blending?


texts: Restrict render in Blender is not working

texts:
I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity.

How can I fix this?


texts: In an iOS OpenGL ES 2 game, is it better to use a few large texture atlas or many small textures?

texts:
I'm working on new game, this time moving to more 3d objects and open gl es 2.  Previous (successful) game was open gl es 1 and mostly 2d.  For es 2 I'm developing my own 3d engine.

My 3d artist delivers .obj's each with a texture map for base and one for bump (normal).  I already have a way to import them all into a single vbo.  But combining the textures is a more challenging problem.

In the es 1 game I did a couple of large texture atlases and could have them all loaded at once.  But since all my geometry was just boxes it was easy to shift them around (small number of vertex) to fit.  I stacked gfx like tetris pieces to fit everything in.  For this though it's a bigger pain to combine textures as there are many many more vertices and they're already mapped to these individual textures.

I have several ideas for ways to approach the problem:

Keep the separate but manage the loading and releasing of texture images better, so that when a level is loaded it loads just the images needed for the objects needed for the level.  If I did this how many images can the ios implementation handle?  How would performance suffer on older devices like the iPhone 4?
Combine multiple textures into atlases and cram image parts together however necessary to fit.  Then load the obj's into my 3d app and basically manually remap everything to the combined texture.  It's a pain and basically what I'm paying the 3d artist to do.
Combine multiple textures into atlases but by putting 4, 8, 16, etc smaller ones into each larger one.. DON'T cram them together but uniformly shrink each one.  Then the remapping can be mathematical instead of a manual remapping.  (This would leave possibly a lot of un-used space in some of the sub-textures)

Pre-calculate the math beforehand in the importing process.
Modify my shader to shrink and offset the textcoord on the fly by an amount provided as a uniform.

Also.. is it better to combine the base texture and normal texture into one or have 2?  Combining them would mean having the shader do math to move the textcoord over for the normal map.


texts: How can I track a "most wins" leaderboard using the Buddy API?

texts:
I work on a mobile game with leaderboards that rank players by most wins. Currently, we've rolled our own, but I am looking to replace this with a SaaS leaderboard solution offering rolling time-based leaderboards (e.g. most wins this week, most wins in the last 30 days, etc.).

One of the leaderboard services I am looking at, Buddy, seems to provide "top score" leaderboards, which is not exactly what I'm looking for. I'm trying to register wins for players with the service and produces a leaderboard by summing the wins for each player for the time period I'm interested in.

How can I accomplish this with Buddy?


texts:
I am developing a simple side scrolling game. I want to target and zoom camera on player when he dies. But it rotates the screen, and I want to prevent it. I'm copying the snippet of code here :

IEnumerator ZoomIn()
{
    while (GameCamera.orthographicSize > 2) {
        yield return new WaitForSeconds (0.01f);
        GameCamera.orthographicSize -= 0.2f;
    }
}

public void ZoomCamera()
{
    CameraZoomSource.Play ();
    StartCoroutine (ZoomIn ());
}

public void TargetPlayer()
{
    transform.LookAt (PlayerTransform);
    GameCamera.orthographicSize = 3;
    GameCamera.transform.Rotate (0, 0, -2);
}

Should I change anything in this?


texts: Unity: Smoothing between two floats which are continuously changing

texts:
I'm looking for some help with smoothing between an original float and a target float, where the original float is consistently changing (potentially interfering with interpolation techniques and or Mathf.SmoothDamp)

I tried Mathf.SmoothDamp with the below:

(float rocketBoostPower is a global variable)

float yVelocity = 0.0F;
float tempForce = rocketBoostPower + Input.GetAxis("Mouse Y") * shiftSpeed / 5f;
rocketBoostPower = Mathf.SmoothDamp(rocketBoostPower , tempForce, ref yVelocity, 0.5f);

This doesn't change the force at all however, it just stays locked in place.

I'm currently using the below to change my power, however I want to smoothly change the power instead of just incrementing sharply on each Update frame:

rocketBoostPower += Input.GetAxis("Mouse Y") * shiftSpeed / 5f;

Please can someone help? I need the assumption that every update will receive a new rocketBoostPower value, whilst still smoothing its previous value.


texts: Any drawback to using rectangular textures over square textures in OpenGL?

texts:
I'm thinking about texture atlas generation where I'd have to choose the dimensions of my atlas, constrained both by my sprites and by the maximum texture size of the current platform.

Given that, is there any drawback to using a rectangular texture over a square texture, assuming the dimensions are still a power of two?  For example, is there a difference between using a 64x256 texture and using a 128x128 texture?


texts:
I'm teaching myself 3D mathematics and in the process building my own rudimentary engine (of sorts). I was wondering what would be the best way to structure my C++ matrix class. There are a few options:

Separate member variables:

struct Mat4 {
    float
        m11, m12, m13, m14,
        m21, m22, m23, m24,
        m31, m32, m33, m34,
        m41, m42, m43, m44;

    // methods

}

A multi-dimensional array:

struct Mat4 {
    float[4][4] m;

    // methods

}

An array of vectors

struct Mat4 {
    Vec4[4] m;

    // methods

}

I'm guessing there would be positives and negatives to each.

From 3D Math Primer for Graphics and Game Development, 2nd Edition p.155:

  Matrices use 1-based indices, so the first row and column are numbered 1. For example, a12 (read “a one two,” not “a twelve”) is the element in the first row, second column. Notice that this is different from programming languages such as C++ and Java, which use 0-based array indices. A matrix does not have a column 0 or row 0. This difference in indexing can cause some confusion if matrices are stored using an actual array data type. For this reason, it’s common for classes that store small, fixed size matrices of the type used for geometric purposes to give each element its own named member variable, such as float a11, instead of using the language’s native array support with something like float elem[3][3].

So that's one vote for method one.

Is this really the accepted way to do things? It seems rather unwieldy if the only benefit would be sticking with the conventional math notation.