texts:
I want to implement (a smooth) lighting into my 2D Maps.
I want to have the basic idea. What I thought of is 2 components.

The Scene's Ambient light:
The Tiles and Sprites are tinted into this colour first.
For example if it's nighttime, the ambient color is very dark so you can barely see anything.

The Scene's Light sources:
The Light Sources have a Radius, intensity and a falloff. The more a tile or sprite is near a light source, the more it gets illuminated by it.

What I thought about the soft lights is that a tile/ sprite has a bounding. Since Tiles are always quadratic, I assume I can interpolate between all four edges of the bounding.The Edges of two neighbouring tiles have the same illumination,similar to vertex lighting in 3D. Does someone have an approach how to start this?


texts: Configure VR support that enables to "look" around and receive user input (Google Cardboard button)

texts:
When the user moves the head this means that the phone in the HMD also moves and there are sensors that can detect the direction of the phone so that the image can update correctly. Also to note that the HMD has a button that can be clicked and trigger an action.
In early 2019, in order to implement both of the above mentioned functionalities (look around and click), stared by configuring Settings > Player > XR Settings and add Cardboard as Virtual Reality SDK. Then, I've used the prefab GVR Editor Emulator. It was basically going to this link, download Google VR SDK for Unity, drag it into Unity and import.
Once the import finished, it's possible to see in Assets a folder named Google VR. The prefab can be found then under Assets > Google VR > Prefabs > GvrEditorEmulator, copy and paste in our scene.
Now, more than 1 year after, when I go to the GvrEditorEmulator page, can see

November 6, 2019 update:

There's a new open source Cardboard SDK that offers a streamlined API, improved device compatibility, and built-in viewer profile QR
code scanning. We recommend that all developers actively building for
Google Cardboard migrate to the new Cardboard SDK: iOS, Android NDK,
Unity XR Plugin (SDK)

What changes in the process considering this update?


texts:
I'm trying to build a simple side scroller with an airplane being the player. As such, I want to build simple flight controls with simple but realistic-feeling physics. I'm making use of cocos2D and Box2D. I have a basic system working, but just can't get the physics feeling correct.

I am applying force to the plane (which is a b2CircleShape) based on the user's input. So, basically, if the user pushes up, body_->ApplyForce(b2Vec2(10,30), body_->GetPosition()) is called. Similarly, for down -30 is used.

This works and the plane flys along with up/down causing it to dive or climb. But it just doesn't feel right. There is no slowdown on climbs, nor speed up during dives. My simple solution is far to simple.

How can I get a better feel for a plane climbing/diving?

Thanks!


texts:
I am building an infinite landscape and I generate all of the terrains procedurally. I recently offloaded my terrain generation code onto another thread to try to eliminate the freeze up when new chunks are loaded, but I've found that:

A) Unity objects and functions cannot be accessed by other threads
B) The slowdown I am seeing is not because of my generation code, but because of adding a mesh collider. If I take away the collider, it runs completely smooth.

My question is is it possible to add a mesh collider async or at the very least use the already calculated mesh values or simplify the collider or optimize it somehow? The frame drops take it from over 220 FPS down to 40 FPS so it's pretty intensive. I wish I could use primitive colliders but the terrain shape is fairly complex and the player has to walk on it.


texts: Library to load images into textures, Linux, C and OpenGl

texts:
I am looking for simple, self-contained C library for Linux to load images from files into OpenGL textures. The licence should be quite liberal: zlib, bsd, mit or something. I have found SOIL, however it hasn't been updated for a long time. Is there something else, or do I have to write my own?

P.S.
I use glfw. There are only deprecated functions for loading images.


texts: Android-Handling screen clicks for dynamically moving objects in a view

texts:
I have a kind of broad question to ask but I have to start some where so.....What is the best way to handle onscreen clicks for moving objects being drawn on a canvas in a view. Im registering the screen clicks just fine and Im able to get the x and y but when it comes to matching it to an object on screen Im at a loss. I have a really hacky way of traversing through an array of existing objects and checking their onscreen coordinates against the coordinates of each item in the array but its no where near reliable and doesnt work most of the time. when it does work the click ends up not matching the item I clicked on. At the moment this all takes place in a custom view and is being drawn on a canvas but in the future Im going to implement it all in opengl when I have the time.....or the money to pay some one else :0)

Any opinions, links to tutorials, or suggestions would be much appreciated thanks.


texts: Semi-transparent mouse cursor on Windows

texts:
I want to change the mouse cursor for a desktop game I am writing with libGDX. That is working well under Linux, however, under Windows semi-transparent cursor pixels are not being rendered at all. That means I am unable to anti-alias the cursor image.

For sure there must be a way to render semi-transparent mouse cursors under Windows, like it's possible under Linux. Any ideas what I could do to solve this issue?


texts: Unity dictionaries having duplicate keys

texts:
EDIT: Restarting Unity solved the problem! ;)

I don't know if Unity and GameObjects have anything to do with this, but I am getting a strange duplicate Key error while scripting in Unity.

static void LoadPartyDataIntoBattle()
{
    foreach (PartyMemberData partyMemberData in ins.TheParty)
    {
        PartyMember partyMemberToAdd = new PartyMember(partyMemberData);
        BattleManager.BattleParticipants.Add(partyMemberToAdd);
        GameObject PartyMemberUI = Instantiate(ins.PMBattlePrefab, ins.PartyFrontRow.transform);

        PartyMemberUIDisplay display = PartyMemberUI.GetComponent<PartyMemberUIDisplay>();
        display.Name.GetComponent<Text>().text = partyMemberData.Name;
        display.Level.GetComponent<Text>().text = partyMemberData.Level.ToString();
        display.HPValue.GetComponent<Text>().text = partyMemberData.HP.ToString();
        display.TPValue.GetComponent<Text>().text = partyMemberData.TP.ToString();

        BattleManager.PMLinkDict.Add(partyMemberToAdd, display);
    }
}

In the line PartyMember partyMemberToAdd = new PartyMember(partyMemberData);, the new keyword should create a different PartyMember on the heap, correct? Yet when I run the debugger, attach it to Unity and play, the second time the foreach loop runs I get a duplicate Key error. For reference, I set the values of ins.TheParty (my list of party members) in the Inspector; there are three partyMembers in TheParty as of now. They have different names, attack, defense, etc. But that doesn't matter, does it? Isn't it the memory location that matters?

I made a test file to mimic the problem I had. It worked fine, no surprises here.

using System;
using System.Collections.Generic;

class Cow { }

class MainClass
{
    static void Main()
    {
        Dictionary<Cow, object> meDict = new Dictionary<Cow, object>();

        List<Cow> myCows = new List<Cow>()
        {
            new Cow(),
            new Cow()
        };

        foreach (Cow c in myCows)
            meDict.Add(c, new object());

        Console.WriteLine("Yay nothing broke"); // this prints just fine
    }
}

I feel like I'm overlooking something obvious, but I can't for the life of me figure out what the problem is. Help appreciated!


texts: unity2D swipe control's bool for animator doesn't work

texts:
i was trying to make a control where the animation plays upon swiping one direction. each time i've make a tap/swipe control, it just keeps popping messages like this. the tap animation works fine, but the animation for swipe controls just doesn't work well, the bool for them has assigned but did not make it 'true' when i swipe a direction, but the bool for the tap works, which is weird.(ignore the miss bool in the animator)

it says that i need to assign the anim variable of the Swipe script in the inspector. but there is nothing left for me to assign, which doesn't make much sense for me. (refer to Region: Animation)

i've tried to make some adjustment with the script, but the results is the same, and it has no problems when build. which is why i need help for the animation stuff.

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

public class Swipe : MonoBehaviour {

public Animator anim;
public bool tap, swipeUp, swipeDown, swipeLeft, swipeRight;
public bool isDragging = false;
public Vector2 startTouch, swipeDelta;

private void Update()
{
    tap = swipeUp = swipeDown = swipeLeft = swipeRight = false;

    #region Standalone Input
    if (Input.GetMouseButtonDown(0))
    {
        tap = true;
        isDragging = true;
        startTouch = Input.mousePosition;
        //Debug.Log("Tapped");
    }
    else if (Input.GetMouseButtonUp(0))
    {
        isDragging = false;
        Reset();
    }

    #endregion

    #region Mobile Inputs
    if (Input.touches.Length >= 1)
    {
        if (Input.touches[0].phase == TouchPhase.Began)
        {
            // tap = true;
            isDragging = true;
            startTouch = Input.touches[0].position;
        }
        else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
        {
            isDragging = false;
            Reset();
        }
    }

    #endregion

    #region Animation
    if (Tap)
    {
        anim.SetBool("Tap", true);
    }

    if (SwipeDown)
    {
        anim.SetBool("Down", true);
    }

    if (SwipeUp)
    {
        anim.SetBool("Up", true);
    }

    if (SwipeLeft)
    {
        anim.SetBool("Left", true);
    }

    if (SwipeRight)
    {
        anim.SetBool("Right", true);
    }

    #endregion

    //calculating the distance
    swipeDelta = Vector2.zero;
    if(startTouch != Vector2.zero)
    {
        if (isDragging)
        {
            if (Input.touches.Length > 0)
                swipeDelta = Input.touches[0].position - startTouch;
            else if (Input.GetMouseButton(0))
                swipeDelta = (Vector2)Input.mousePosition - startTouch;
        }

    }

    //did we cross the deadzone?
    if (swipeDelta.magnitude > 125)
    {
        //which direction?
        float x = swipeDelta.x;
        float y = swipeDelta.y;
        if (Mathf.Abs(x) > Mathf.Abs(y))
        {
            //left or right
            if (x < 0)
                swipeLeft = true;
            else
                swipeRight = true;
        }
        else
        {
            // Up or down?
            if (y < 0)
                swipeDown = true;
            else
                swipeUp = true;
        }
    }

}

public void Reset()
{
    startTouch = swipeDelta = Vector2.zero;
    isDragging = false;
    anim.SetBool("Tap", false);
    anim.SetBool("Down", false);
    anim.SetBool("Up", false);
    anim.SetBool("Left", false);
    anim.SetBool("Right", false);
}

public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool Tap { get { return tap; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }

}


texts:
These functions sample multiple RGBA pixels but return only a single component.
OpenGL: https://www.opengl.org/sdk/docs/man/html/textureGather.xhtml
DirectX: https://msdn.microsoft.com/en-us/library/windows/desktop/ff471525(v=vs.85).aspx

If you were to use this on an RGBA texture, and only gathering the red component, would the texture cache get loaded with the RGBA values, or would it only load the R values?

I'm curious because not all cards in use today support A8 textures (or other single channel 8 bit textures), and a workaround would be to store the data in 1/4 as many pixels by using RGBA and only grabbing the channel needed.

If this sounds obscure, a down to earth practical usage case is distance field textures.

Trying to see if using these functions would be a good alternative to cards that don't support A8.

Thanks!


texts:
I have a problem where the bodies in my debug draw does not draw correctly, take a look:

As you can see, there is some space between the dynamic body and the ground. I have checked the contact listeners and they are indeed colliding, but with a space inbetween. The contact point is not drawn either, which gives the hint of some drawing error (?).

My PPM = 100. If I set it to 1, the problem disappears (dafuq), but that's not really feasable to have a 1 pixel/meter ratio. I have tried to play around with the cameras but without result. Here is a simplified snippet from my screen:

public class GameScreen implements Screen {

    private OrthographicCamera cam;
    private OrthographicCamera b2dcam;

    private World world;
    private Box2DDebugRenderer b2dr;

    private static final float PPM = 100;
    private static final int V_WIDTH = 160;
    private static final int V_HEIGHT = 90;

    public GameScreen() {
        cam = new OrthographicCamera();
        b2dcam = new OrthographicCamera();
        b2dr = new Box2DDebugRenderer();
        world = new World(new Vector2(0, -9.82f), true);

        /* ... create bodies etc ... */
    }

    public void render(float delta) {
        /* I actually use more complex fixed timestep - just simplified here */
        world.step(1/60f, 6, 2);

        // Render
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Align the b2dr renderer to the camera
        b2dr.render(world, cam.combined.cpy().scale(PPM, PPM, 1));
    }

    public void resize(int width, int height) {
        float aspectRatio = (float) width / (float) height;
        float aspectRatio2 = (float)height / (float)width;

        // This is to maintain the same aspect ratio, using virtual screen-size
        if(aspectRatio >= (float) V_WIDTH / (float) V_HEIGHT){
            cam.setToOrtho(false, V_HEIGHT * aspectRatio, V_HEIGHT);

        } else {
            cam.setToOrtho(false, V_WIDTH, V_WIDTH * aspectRatio2);
        }

        cam.update();
    }
}


texts:
I am currently finding an issue with my midpoint algorithm,  I have been given a formula to work out the midpoint algorithm, but it seems to not correctly orbit. The aim is to get a more accurate version of the EulerMethod to create an more approximate orbit across all frame times.  As the EulerMethod will cause a bit of an inaccurate orbit based on different frame-rates.

1st use Euler’s method to approximate half - way position / velocity :
position after half frame = current position +
half frame time * current velocity
velocity after half frame = current velocity +
half frame time * current acceleration

Calculate forces at half - way position to get half - way acceleration
Then use Euler’s method again with updated info :
position next frame = current position + frame time * halfway velocity
velocity next frame = current velocity + frame time * halfway acceleration

The method causes the 2nd sphere to move diagonally infinitely to the bottom right.

The Algorithm

void midpointmethod(CVector3& position, CVector3& velocity, CVector3& centre, float updateTime)
{
    CVector3 accel = OrbitAcceleration(position, Length(velocity), centre);
    //position = position + updateTime / 2 * velocity * updateTime;
    //velocity = velocity * updateTime / 2 * accel.Length() * updateTime;

    CVector3 halfpos = position + (updateTime / 2) * velocity;
    CVector3 halfveloc = velocity + (updateTime / 2) * accel;

    // calculate forces ?
    CVector3 halfwayaccel = accel / 2;

    CVector3 posnexf = position + updateTime * halfveloc;
    CVector3 velosnexf = velocity + updateTime * halfwayaccel;

    position = posnexf;
    velocity = velosnexf;

}


texts: How do I use get_action_strength in Godot?

texts:
I get the error:

  Invalid call. Nonexistent function 'get_action_strength' in base 'InputDefault'.

extends KinematicBody2D

export (int) var speed = 400
export (float) var rotation_speed = 10

var velocity = Vector2()
var rotation_dir = 0
var stance = 0

func ready():
    Input.action_set_deadzone("left", 0.25)
    Input.action_set_deadzone("right", 0.25)
    Input.action_set_deadzone("up", 0.25)
    Input.action_set_deadzone("down", 0.25)

static func angle_to_angle(from, to):
    return fposmod(to-from + PI, PI*2) - PI

func get_input():
    var left_joy_axis_h = Input.get_action_strength("right") - Input.get_action_strength("left")
    var left_joy_axis_v = Input.get_action_strength("up") - Input.get_action_strength("down")

    rotation_dir = 0
    velocity = Vector2()

    if(Input.is_action_just_pressed("stance")):
        if(stance == 0):
            stance = 1
        else:
            stance = 0
    if(stance == 0):
        velocity = Vector2()
        velocity += Vector2(speed, 0) * left_joy_axis_h
        velocity += Vector2(0, speed) * left_joy_axis_v
        if(angle_to_angle(rotation, velocity.angle()) > 0):
            rotation_dir = 1;
        elif(angle_to_angle(rotation, velocity.angle()) < 0):
            rotation_dir = -1;
        else:
            rotation_dir = 0
    elif(stance == 1):
        rotation_dir = (Input.get_joy_axis(0,7) - Input.get_joy_axis(0,6))

        velocity = Vector2()
        velocity += Vector2(speed, 0).rotated(rotation + PI/2) * Input.get_joy_axis(0,0)
        velocity -= Vector2(speed, 0).rotated(rotation) * Input.get_joy_axis(0,1)

func _physics_process(delta):
    get_input()
    rotation += rotation_dir * rotation_speed * delta
    move_and_slide(velocity)


texts:
In My layout
parent as Relative layout and then am having Scroll view
inside Linear layout
now am having child views as Image view Text View Web view and Recycle view and 2 buttons is there
now i want to pinch in zoom entire layout

please help me out
Regards
Govardhana


texts: Can a local UDK server have two clients connected locally?

texts:
To do some basic testing on players interacting with other players I would need to have at least two players in my world. My solution is to run the server from my computer, then run two clients. When I run the second client and connect to the server, I find a weapon dropped by client 1 in the appropriate position(but no body). What happened?

server.bat:
C:\UDK\UDK-2015-01\Binaries\Win32\UDK.exe server ieTestMap?GoalScore=0?TimeLimit=0?Game=ie.ieGame  -log

client.bat:
C:\UDK\UDK-2015-01\Binaries\Win32\UDK.exe 127.0.0.1 -log

class ieGame extends UTDeathmatch;

simulated function PostBeginPlay()
{
}
defaultproperties
{
    bScoreDeaths=false
    PlayerControllerClass=class'ie.iePlayerController'
    DefaultPawnClass=class'ie.iePawn'

    bDelayedStart=false
    GameReplicationInfoClass=class'ie.ieGameReplicationInfo'
}

class iePlayerController extends UTPlayerController;
reliable client function ClientSetHUD(class<HUD> newHUDType)
{
    if(myHUD != none)
        myHUD.Destroy();

    myHUD = spawn(class'ieHUD', self);
}
defaultproperties
{
}

I have kept the other classes of my game 'bare-bone.'


texts: What are different types of online game formats besides Flash?

texts: I am currently looking into making a website that hosts various online games and would like to support as many formats as possible no matter how obscure. I was wondering if anybody could inform me on what these different formats(Flash, JavaScript, etc.) may be and possibly even provide me with some insight on how to embed them.


texts: Best way to go with 3D dungeon crawler generation

texts:
I'm trying to prototype a little 3D dungeon crawler. That is, the same system as any rogue-like : A map with little rooms, linked by hallways.

But in 3D. The world is still in blocks, but I can go up and down. This game is a nice exemple of what I want. I still want the world to be mostly flat (for exemple every room could be at the same height) but I need some little up-and-downs in the rooms, or the hallways between them.

I already tried 2D dungeon generation with no precise algorithm (just by myself) but I think this time it would be best to have some nice algorithm and a good workflow about it.

So I need help about this :

A nice 3D generation
What data structures should I use to store my levels ?
How should I then create it ? I'm on Unity, and for now I am associating an enum to prefabs for each type of map blocks, and then I instantiate every case. Is it a good way of doing this ?


texts: How to make objects collisions act differently

texts: I am making an arkanoid type game and have it mostly working.  I can destroy the bricks when hit by the ball, but I am adding a twist.  I want to have a object on top of the bricks that will interact with the bricks but not destroy them.  It needs to still be affected by gravity and collisions because when you collect them all you win the game(you collect them by getting rid of the bricks below them.  Everything is pretty much working except for when this object collides with the bricks it triggers the destroy function within the brick script.  I am using C# and unity 4.6.9.  Thanks in advance!  I can give pictures and scripts if people want, IDK what would be exactly relevant here though because I'm not sure if this is something done in unity, in the brick script, or in the falling object script.


texts:
I have this code where I can draw as many rectangles I want without no VAO/VBOs warm up.

// Shader sources
const GLchar* vs = R"glsl(
    #version 330 core

    vec2[4] position = vec2[4] (
        vec2(0.5, 0.5),   vec2(0.5, -0.5),
        vec2(-0.5, -0.5), vec2(-0.5, 0.5)
    );

    void main()
    {
        gl_Position = vec4(position[gl_VertexID] - 0.5, 0.0, 1.0);
    }
)glsl";

const GLchar* fs = R"glsl(
    #version 330 core
    out vec4 outColor;

    void main()
    {
        const vec3 color = vec3(1.0, 0.5, 0.2);
        outColor = vec4(color, 1.0);
    }
)glsl";

void useShader(const char *vs, const char *fs) {
    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vs, NULL);
    glCompileShader(vertexShader);

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fs, NULL);
    glCompileShader(fragmentShader);

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);
}

int main()
{
    //..window, gl init..
    GLuint elements[6] = {  0, 1, 3,  1, 2, 3 };
    while (true)
    {
        // Clear the screen to black
        glClearColor(0.4f, 0.4f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw a rectangle from the 2 triangles using 6 indices
        useShader(vs, fs);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, elements);

        // Swap buffers
        window.display();
    }
    // cleanup
    return 0;
}

Why aren't any VAOs/VBOs needed. I've understood that VBOs are basically buffers that hold different kind of data that will be sent to the GPU. Basically, are vao/vbo usefull only for loading data into the shaders, since I'm gonna need constant data, wouldn't be better to premake the shaders and use them whenever I need them, or do I need to do it the VAO way.

Also when I'm looking to change the layout origin to upper left it logs me that it needs input data oO..


texts: Novice Mobile Game Developers | Publishing on our own or Publisher?

texts:
So we are almost done with our first indie game, developed on Android. We believe that the game has potential, our graphics guy is damn good so we have some good eye candy in our game.

Now we are thinking what should be our starting step? We can purchase the Google Play account and launch it on our own, but we aren't sure if we'd be able to advertise it well and get something big out of it.

Or we can contact a publisher, and talk about some deal.

Which one is better? What are the pros and cons of both, considering this is only our first game and we intend to make a lot more. Also considering that we're only students yet, currently in our senior year. We would love to generate some revenue out of it.

What are the best ways of contacting publishers? How do we approach them and deal with them?

Many thanks for your kind help!


texts: How to represent cliff faces in terrain?

texts:
I'm trying to figure out the best way to programmatically represent terrain in my game. I've been considering using a heightmap (or grid of evenly spaced vertices) to represent the surface of the terrain and a splatmap to allow smooth texturing. This would work for totally smooth terrain, but the problem is how to represent cliffs and sharp cliff faces.

The cliffs themselves would need to be rendered differently than the rest of the terrain. For example, they would need to have a different (non-stretched) texture visible on the front of the cliff, but if I used the splatmap for this, it would be impossible to have a sheer enough cliff face where the texture of the cliff is totally separate from the ground.

A picture says a thousand words so...

What are some general ways to store and/or render cliffs and other sharp differences in terrain height?


texts: What is the cause of these WaitForFPS spikes and dips?

texts:
In Unity, moving the player causes the camera to jitter. I went to the Profiler, and I saw these spikes:

On further inspection, all the yellow spikes were WaitForFPS(). I've tried every VSync setting in quality options, but none of them seem to fix this issue.


texts: Which gesture recognizer should I use to handle multiple simultaneous flicks?

texts:
So, if you can picture a game with little ninjas running down at you, and a bunch of shurikens at the bottom of the screen, you're picturing the set-up I'm addressing.

I want the player to be able to flick the shurikens up at the ninjas, but I want them to be able to do it with both thumbs at the same time. Gesture recognizers seem to be the way to do this, but I'm not sure which is the most appropriate. The main ones that seem to fit are the pan gesture and the swipe gesture.

Does anyone have insight into the pluses and minuses of each, or even if a better one exists?


texts: LibGDX: TextureRegion renders correctly, but .getTexture() doesn't

texts:
I have a TextureRegion that I get from an atlas map (which in turn I get from the Asset Manager), eg

AssetManager am = myGame.getAssetManager();
TextureAtlas atlas = am.get("my.atlas", TextureAtlas.class);
TextureRegion object = atlas.findRegion("myobject");

Now when I draw the object with

batch.draw(object, ...);

the object is drawn correctly, but if I do

batch.draw(object.getTexture(), ...);

it is drawn as garbage. Is this expected? I thought it should work the same.


texts: Getting the topleft, topright, bottomleft and bottomright points of a shape in Unity3D?

texts:
I have a 4-point shape that is defined in screen space by the user.
They can draw the 4 points, one at a time, in any order they wish.

I am using a List of Vector2's to store the screen co-ordinates of each point.

Now what I'm trying to do is figure out how to get which of each of those 4 points are the topleft, topright, bottomleft and bottomright points of this shape, but I'm not having any luck.

I've tried using topleft = MinX, MinY etc, but obviously this doesn't work as the topleft point doesn't necessarily contain both the MinX and MinY value.

Can anyone point me in the right direction.

Thanks


texts:
I've just downloaded the latest headers from the OpenGL registry and included them in my project. I am attempting to create an OpenGL 3+ context. Every tutorial/resource has used wglCreateContextAttribsARB to do this. However, this does not seemed to be defined in the headers I have.

#include <Windows.h>
#include <gl\GL.h>
#include "glcorearb.h"
#include "glext.h"
#include "wglext.h"
...
wglCreateContextAttribsARB = // Not recognised
(PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); // Recognised (Why this and not the function name?)

The closest existing function is wglCreateContext, which I don't believe is what I want.

In the wglext.h header, there is this though:

typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
#ifdef WGL_WGLEXT_PROTOTYPES
HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList);
#endif

And that can get me the function, but is defining WGL_WGLEXT_PROTOTYPES really the "correct" way to do what I want?

I haven't been able to find any information on the issue, what is the correct procedure? And where can I find information on changes/problems like these?

I'm not interested in using any extension loading libraries such as GLEW to handle this.

Thanks.


texts: What program was used in Kojima's Death Stranding to create the 3D scans of people?

texts: I've been unable to find out what program Hideo Kojima used to create his 3D scans of people in his game Death Stranding and presumably Metal Gear V as well. Here is a video of the scanning in progrees (Starts at 4:45 https://www.youtube.com/watch?v=KlMpN26ts7s).


texts: Enable/Disable an image inside an if statement

texts:
Basically i have a code that changes the skybox after killing x amount of enemies, and i want to enable and disable four pictures inside the two if statements. I tried making three public images, set them to false and then enable them inside the every if statement but i'm pretty sure that's not how it works. I'm a noob. Here's the code:

public class enemyCount : MonoBehaviour {

    public static int enemiesCount = 15;
    public Material mat1;
    public Material mat2;
    public Material mat3;

    void Start () {
    }

    void  Update (){
        print("Enemy Count is " + enemiesCount);

        if(enemiesCount <= 10)
        {
            Debug.Log("Level 2!!!");
            RenderSettings.skybox = mat2;
            //Heres should display image number 1
        }

        if (enemiesCount <= 5) {
            Debug.Log ("Level 3!!!");
            RenderSettings.skybox = mat3;
            //Here should display image number 2
        }

        if (enemiesCount <= 0) {
            Debug.Log ("YOU WON");
        }
    }
}


texts: In Game Maker, how do I make invisible platforms the player can walk on, and reveal with an item?

texts:
I'm using Game Maker and looking for help with these:

I'd like to have invisible platforms and walkways for the player to move on. I want the platform to be slightly visible in this option so the player can find them but still be invisible while being fair to the player.
Platforms are invisible, but a special item (like the Lens of Truth in Legend of Zelda: Ocarina of Time turns the invisible things visible within a given area for the time the player is using the item.


texts:
I use blender game engine and blender uses OpenGL for graphics. How can I draw lines around all 3D objects? Would this be a job for a filter? Mainly, I want my end result to look drawn.
I found this:
uniform sampler2D bgl_RenderedTexture;
uniform sampler2D bgl_DepthTexture;

void main()
{
   float depth = texture2D( bgl_DepthTexture, gl_TexCoord[0].xy).r;
   float depth2 = texture2D( bgl_DepthTexture, gl_TexCoord[0].xy + vec2(0,0.002)).r;
   float depth3 = texture2D( bgl_DepthTexture, gl_TexCoord[0].xy + vec2(0.002,0)).r;

   float fac = abs(depth-depth2) + abs(depth-depth3);

   float intensity = 9050;

   vec4 sub = vec4(fac*intensity,fac*intensity,fac*intensity,0);

   gl_FragColor = texture2D( bgl_RenderedTexture, gl_TexCoord[0].xy ) - sub;
}

#change float intensity

here and that seems to work, but I need it to look more sketched. So I would like some noise influence. Maybe it's called sinus displacement? Is there a way to do that?
I draw and I want the style to look like this. Thanks.
Disclaimer: I do hang out on BSE and this is not a question they are prepared to answer or is it necessarily on-topic for them, since it is about OpenGL.


texts:
I'm working on a Unity's Project and I want to modify a prefab, more precisely I want to change the texture of a prefab. The problem is that my modification is applied also to other prefabs. I read on the documentation how each of the buttons labeled Select, Revert and Apply works, and what I understood is that the modification should update only the selected prefab.

Here is the Prefabs' Manual which I read.

What am I missing?

PS: I'm not the author of the project, I have to apply some modifications only.


texts:
I'm having some trouble implementing a homing missile that satisfies what I'm looking for. I have already tried the Seeking and Arrival behaviours described in this link, but none of them were what I wanted. With Seeking, it winds up orbiting the object indefinitely, and Arrival is simply unavoidable.

I'm aiming for something similar to the missiles of this video and the ones of Super Meat Boy - avoidable missiles that nevertheless do the job. It actually looks like a mix of Seek and Arrival, or maybe even the Path Following behaviour described in the first link.

This is my idealized behaviour, with a user-controlled target:

Can I have some insight on the matter? I know that questions regarding homing missiles have popped up quite often around here, but I feel that I'm missing something basic. The first video has an explanation from its creator in the second answer of this question, I didn't quite grasp it, though.


texts: Material is missing after build with Unity Cloud

texts:
when I tried to build with unity cloud, materials aren't in the build.
there is no specific shader I just used the default URP material.

after a while, I found the problem.
when I import new models I have to make the new material and replace it with the default material so there is no problem after the build.
but I want to know is there a better solution to this problem.

I also checked my unity cloud build report and there weren't any errors related to URP or materials


texts:
I have been trying to create my very first game for quite a while, followed some tutorials and stuff, but I am stuck at creating my entity system. I have made a class that extends the Entity class and here it is:

  public class Lazer extends Entity{//Just say that it is some sort of bullet

private Play p;//Play class(State)
private float x;
private float y;
private int direction;

public Lazer(Play p, float x , float y, int direction){
    this.p = p;
    this.x = x;
    this.y = y;
    this.direction = direction;
    p.ent.add(this);
}

public int getDirection(){
    return direction; //this one specifies what value will be increased (x/y) at update
}
public float getX(){
    return x;
}
public float getY(){
    return y;
}
public void setY(float y){
    this.y = y;
}
public void setX(float x){
    this.x = x;
}
     }

The class seems pretty good , after speding some hours googling what would be the right thing.
Now, on my Play class. I cant figure out how to draw them. (I have added them to an arraylist) On the update method , I update the lazers based on their direction:

public void moveLazers(int delta){
       for(int i=0;i<ent.size();i++){
           Lazer l = ent.get(i);
           if(l.getDirection() == 1){
               l.setX(l.getX() + delta * .1f);
           }else if(l.getDirection() == 2){
               l.setX(l.getX() - delta * .1f);
           }else if(l.getDirection() == 3){
               l.setY(l.getY() + delta * .1f);
           }else if(l.getDirection() == 4){
               l.setY(l.getY() - delta * .1f);
           }

       }
   }

Now , I am stuck at the render method. Anyway , is this the correct way of doing this or do I need to change stuff? Also I need to know if collision detection needs to be in the update method. Thanks in advance ~ Teo Ntakouris


texts: OpenGL Orthographic projection questions

texts:
I'm studying now about projections with OpenGL and I've some questions:

Is there importance for the viewer's location? I know if I move forward/backward it won't mind, but what if I move upward with 30 degrees for e.g.

Does the viewer is located in the 0,0,0 axis? or he can be in another place after defining glOrtho's properties.

Are there only 6 projections? (I'm asking this because of the properties of the box, and defining the glOrtho - near, far, left, right, up, bottom)

Can I hide objects with ortho proj? I think it's obvious that yes, but I'm still curious maybe I'm wrong.

Do objects that are closer to me seem bigger, meaning that other objects may be hidden? I believe that not. the objects don't seem bigger. they stay the same size.


texts: How should I manage game levels in a flash games?

texts:
I am still learning and I am trying to design the game levels for my first game (a platformer).

I have some straightforward questions because I feel I am on the wrong way.

Should each level have its own class ?

The way I am trying to do this is, when one finishes the first level I set all variables to null that belong to that class, unregister all events and remove all children from the stage, call a second level constructor, without declaring any variable, new level2(); and set a static var to true "in order to save" that progress in case one wants to play that level again.

However I see the code becomes messy, I run into issues, and memory management concerns arise.

I searched for help all over the internet but I can't find any tutorial that explain it in details, so I'm trying out many ways of achieving what I want, but now I am really in need of some advices to not get lost.


texts: Simple Collision Resolution between 2 moving objects

texts:
I have two circles. And they can move in any direction. Their movement is based on these values:

circle1.xSpeed & circle1.ySpeed

And the same for the second circle. Now I know when they collide with eachother:

var dx = this.x - other.x;
var dy = this.y - other.y;
var intersectDist = (this.scale + other.scale) - Math.sqrt(dx * dx + dy * dy);
if (intersectDist >= 0) {
    // MOVE OBJECTS APART:
    intersectDist /= 2;
    this.x -= intersectDist * Math.cos(this.dir);
    this.y -= intersectDist * Math.sin(this.dir);
    other.x -= intersectDist * Math.cos(other.dir);
    other.y -= intersectDist * Math.sin(other.dir);

    // ADJUST VELOCITY: (STUCK HERE)

}

Im not sure if that is the best way to move the objects apart, but the main issue is the resulting x and y speeds for each object. How can I calculate those?


texts: Why does unity obj import flip my x coordinate?

texts:
When I import my wavefront obj model into unity and then draw lines over it with the same coordinates in the obj file, the x coordinate is negated.

I don't see any option in the importer that might be doing that.  And I'm using the same localToWorldMatrix and the same coordinate data in the .obj file.  Hmmm

GL.PushMatrix();
GL.MultMatrix(transform.localToWorldMatrix);

CreateMaterial();
lineMaterial.SetPass(0);

GL.Color(new Color(0, 1, 0));
GL.Begin(GL.LINES);

GL.Vertex(p1);
GL.Vertex(p2);

GL.Vertex(p2);
GL.Vertex(p3);

//...

GL.End();
GL.PopMatrix();


texts: How to deal with cheat avoidance and trusted client issue

texts:
I hope not to be off-topic here.

At the moment I'm dealing with networking programming for the game I'm working on and I found different possible scenarios.

I started to build code using a Platform as a Service such as Photon Unity Network which offers a quite simple system to sync players through its cloud.

The problem is that by using the cloud you must have at least a trusted client in order to prevent cheating from players.

I wish I could learn what is best to deal with this problem considering that opting for a client/server structure would be the best but I'm a bit worried about rental/purchase pricing. Is there a cheap way to have a working game server?


texts: How do I create a big multiplayer world in UDK?

texts:
I want to create a big multiplayer world in UDK and I'm having a few difficulties.

I created the biggest terrain possible but then any terrain related action I do takes forever. However, I've seen videos of people make same size terrain and working without a problem. My pc is strong enough, so maybe someone can tell me what I'm doing wrong.
I want to make it even bigger then the biggest terrain size, so I was thinking of doing level streaming but then I read that streaming is working server side which means if I have a player on every terrain all terrains will still be loaded and I want to save as much memory possible so it will work well online.

Thanks for any help you can give.


texts: RPG game engine. Skill application calculations

texts:
Short preface
I am a part of a small team which is entering game development. We're creating a new RPG setting with custom game system and mechanics based on dice rolls. I'm server-side java programmer, so the game engine is my responsibility.
The problem
I have a problem designing talent classes. Each character may have a set of talents. The problem is, most talents are unique and different from others. For example:
Talent Season fever gives character a stat bonus depending on the season of the year, e.g. strength +2 in Winter, dexterity +2 in Spring, etc. Which gives player an opportunity to add and swap talents because of changed stats four times a year.
Talent Fortune Wheel allows a player to roll d6 each morning and get a bonus on one of the six stats (strength, dexterity, etc.) for that day.
Talent Attuned to partner gives a player +2 on his hit roll if his character has exactly one partner in the battle. If his partner also has this talent, both of them get +4 instead.
As you see mechanics of each talent are different. Question is how to universally implement all this different functionalities in Java classes.
Some technical details
I use latest version of JDK 7.
Springframework stack (spring-data, spring-mvc, spring-security, etc.)
MongoDB for persistent storage.
My ideas
The solution I came up with:

Create a parent Talent class with generic fields and methods, like
id, name, description, requirements to obtain, etc. and an abstract apply() method.
For each talent in the game extend Talent class and add custom logic by implementing the apply() method.
I also need some trigger mechanism (I don't really know how it would look, so please advise if you have ideas). For example, if character has some talent which gives him bonus to a melee attack in some situations (preconditions) the trigger would fire on each event of melee attack made by the player, when the trigger fires it also checks if preconditions are met and if they are it calls the apply() method of a talent.
I have to implement scheduling for triggering or processing talents which depend on times or periods like the Season fever talent described above.

Disclaimer
I have really small experience of asking questions on stack-exchange, so feel free to point out suggestions on question format and additional info required. Also, English is not my native language, so feel free to correct me if something annoys you (grammar-nazi style)


texts: How to make Procedual Context Sensitive Mesh Generation during Runtime

texts:
In the game that i am trying to make i essentially generate an infinitely generating maze that has no dead ends and each corridor is of the same width.

i have successfully managed to create this system however once i have created the floor tiles on which you are supposed to walk on i need to generate some walls. these walls surround the floor tiles preventing you from leaving the floor tiles. the system that i have for making these walls right now is very inefficient and redundant so, i would like to find a better way of doing so.

my current system for making these walls:

first, a Floor Builder lays out all the required floor tiles then i have a wall builder game object with numerous empty games objects in a single row that each have a script attached to them that checks if there is a collision on their current tile. if there is a floor tile nothing happens else a wall game object is spawned which is essentially a 1x1x1 cube that has a collider attached to it. once all the checks have been done the parent game object is move 1 tile upwards and the process repeats itself.

once the player is out of range of the walls that are left behind a garbage cleaner game object just destroyed them.

this system can be improved in terms of code by using arrays instead of multiple game objects however that would still not improve the performance since the cause of the performance drop on slower devices it that a lot of game objects have to be spawned and tracked. the whole system is very inefficient and produces about 100 to 500 game objects which are destroyed later on.

i have attached a picture to give an idea of how the system works ignore the cubes and other entities.

there are also other solutions i have looked into and made

Single line Builder:

basically, at the boundary, i put a single game object that starts and stops when a player is nearby or not it goes from right to left checking each 1 unit of space for a floor tile and spawning a wall if there isn't. this was a much more efficient but slow solution which i later improved on.

Smart Single line Builder:

its mostly the same as the previous one however once it is in an empty spot it fires a raycast on its left side and when that ray hits a floor tile it uses the information obtained with its current coordinates to make a single row big wall instead of multiple walls this system worked much better but was still so slow that the player is able to run faster than the system can make walls.

The kind of system that i would like to have:
a simple quad that sits below the floor tiles and moves along with the player.
the quad is essentially pulled upwards in places where there isnt a floor tile. i have no idea how to make something like this.


texts: Is this Possible to force gameobjects (coliders etc) to get stretched based on the aspect ratio of the screen?

texts:
Well with unity3D, I am in big trouble whenever I use sprites. As for textures I compensate for a evener look by Stretching it (Screen.width & Screen.height- that's fine for low end 2D games). Now If I have an Image and based on content of Image (Let's say I want to add BoxCollider for the walls in image). It works, but for only one aspect ratio. As I am making game for Android. I am having bunch of different resolution & Aspect ratios. Is this possible to stretch my coliders or other game objects so that I can Work easily????
please help me. I am in a rush :(


texts: Implementing a score system similar to Moon Patrol

texts:
I am working on an Android game scenario inspired by Moon Patrol.

My beta version is available for beta test from https://play.google.com/store/apps/details?id=dev.android.buggy

In my case, I got the elapsed time in seconds for reaching a checkpoint, and I could reward either a fixed bonus or a bonus based on the time, perhaps the difference between the time and the average time, or another bonus if it is a high score. My specific implementation for completing a checkpoint looks as follows at the moment:

if (checkpointComplete) {
    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //
        }
    });
    canvas.drawColor(Color.BLACK);
    ((ParallaxActivity) getContext()).stopWatch.stop();
    paint.setTextSize(60);
    String s2 = "TIME TO REACH POINT \"" + Background.checkpoint + "\"\n";
    if (runOnce) {
        for (int q = 0; q < s2.length(); q++) {
            final String s2f = s2;
            final int r = q;
            ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    checkpointtextview.setTextColor(Color.RED);
                    checkpointtextview.append(Character.toString(s2f.charAt(r)));
                }
            });
            try {
                Thread.sleep(50);
            } catch (InterruptedException ie) {
            }
        }
    }
    String str = String.format("%03d", ((ParallaxActivity) this.getContext()).countUp);
    String s3 = "YOUR TIME                :   " + str;
    if (runOnce) {
        for (int q = 0; q < s3.length(); q++) {
            final String s3f = s3;
            final int r = q;
            ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    checkpointtextview2.setTextColor(Color.parseColor("#ADD8E6"));
                    checkpointtextview2.append(Character.toString(s3f.charAt(r)));

                }
            });
            try {
                Thread.sleep(50);
            } catch (InterruptedException ie) {
            }
        }
    }
    runOnce = false;
    // canvas.drawText("CHECKPOINT COMPLETE", (float) (screenWidth * 0.35), (float) (screenHeight * 0.45), paint);
    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((ParallaxActivity) getContext()).startTime = SystemClock.elapsedRealtime();
                    ((ParallaxActivity) getContext()).stopWatch.setBase(((ParallaxActivity) getContext()).startTime);
                    ((ParallaxActivity) getContext()).stopWatch.start();
                    checkpointtextview.setText("");
                    checkpointtextview2.setText("");
                    checkpointtextview3.setText("");
                    checkpointtextview4.setText("");
                    checkpointtextview5.setText("");
                    checkpointtextview6.setText("");
                    String str = "Player 1  " + String.format("%06d", score);
                    tvId.setText(str);
                    scoring = false;
                    buggyXDistance = 0;
                    distanceDelta = 0;
                    retardation = 0;
                    checkpointComplete = false;
                    runOnce = true;

                }
            }, 3000);
        }
    });
}

I want to calculate bonus for completing a checkpoint but how is it calculated? If we look at the original it looks like below.

Is it possible to deduce the formula for calculating the bonus? My bonus screen looks the same. So if your time is x and the average time is y and the record is z, what is the formula?


texts:
I have created a menu class and now I'm working on getting it to render using OpenGL's VBO's. The menu is fairly simple, it has a number of buttons, the user can press up and down to highlight the desired button and then press ENTER to go to the selected buttons sub-menu which is just another instance of my menu. It should be noted that it doesn't need to have the same amount of buttons as the previous one. Pretty basic.

What I've come up so far is this:

//setting up the buffers and variables
int amountOfVerticesButtons = this.menu.getCurMenu().getNoButtons() * ShapeRenderUtils2D.VERTICES_RECT;
FloatBuffer vertexBufferButtons = BufferUtils.createFloatBuffer(amountOfVerticesButtons * VERTEX_SIZE);
FloatBuffer colorBufferButtons = RenderUtils.createColorBuffer(0.5f, 0f, 0.5f, amountOfVerticesButtons);

int amountOfVerticesBorders = this.menu.getCurMenu().getNoButtons() * ShapeRenderUtils2D.VERTICES_FRAME;
FloatBuffer vertexBufferBorders = BufferUtils.createFloatBuffer(amountOfVerticesBorders * VERTEX_SIZE);
FloatBuffer colorBufferBorders = RenderUtils.createColorBuffer(0.3f, 0f, 0.45f, amountOfVerticesBorders);

//filling up the buffers
for (int i = 0; i < MAX_BUTTONS_PER_PAGE && i < menu.getCurMenu().getNoButtons(); i++) {
    //buttons
    vertexBufferButtons.put(ShapeRenderUtils2D.getRectVertices(new Point(point.x, point.y + (i * (BUTTON_HEIGHT + BUTTON_SPACING))), MENU_WIDTH, BUTTON_HEIGHT));

    //button borders
    vertexBufferBorders.put(ShapeRenderUtils2D.getFrameRectangle(new Point(point.x, point.y + (i * (BUTTON_HEIGHT + BUTTON_SPACING))), MENU_WIDTH, BUTTON_HEIGHT));
}

vertexBufferButtons.flip();
buttons_handles = RenderUtils.createHandles(vertexBufferButtons, null, colorBufferButtons, amountOfVerticesButtons);

vertexBufferBorders.flip();
borders_handles = RenderUtils.createHandles(vertexBufferBorders, null, colorBufferBorders, amountOfVerticesBorders);

This code is run once in the constructor and it sets up the VBO for my buttons, and creates a color array with one color for each button.

My question is:

When the user presses ENTER, a new menu becomes active. The new menu doesn't have to have as many buttons as the previous one, so the old VBO is worthless, because it is of different size. I detect that the menu changes and what I basically do is to run the above code again, for the new menu, but at the end before I flip and create Handles I first do:

RenderUtils.deleteHandles(buttons_handles);
RenderUtils.deleteHandles(borders_handles);

Which removes the handles to the old VBO's. And then I create new ones just like I did the first time, but this time with correct size.

This seems very ineffective. Is there a better way to do it? Is there a better way to change an existing VBO's size?

EDIT: Please note that I've got everything else done with the menu. I only have problems with the VBO rendering. Also, there may be a very large amount of buttons, with many sub-menus that also contain large amounts of buttons, so creating a separate VBO for each case is not possible.


texts: Decoupling input from game states / entity behavior

texts:
I'm looking for a way or general best practice advices for decoupling the architecture of my game, in the example below the input from the current game state workflow / entity behavior. While I'm all in for certain game development (or general) patterns such as an event- or component-driven design, I'm failing to understand how a decoupled architecture can work in a case where e.g. an entity actually needs to know a little bit more.

Take for example this little (bad) example:

// some component attached to an entity
void Update(long elapsedTime) {
    var keyboardState  = _keyboardDevice.State;
    var gameState      = _gameStateStack.CurrentState;

    if(keyboardState.IsPressed(Keys.Enter) {
        if(gameState.GetType == typeof(MenuState))
            ((MenuState)gameState).ExitMenu();
        } else {
            parent.Jump();
        }
    }
}

The requirements are pretty simple: If we're in the game menu, pressing enter closes the menu. However if the menu is not active, pressing enter causes the entity to jump. If I'm going to decouple the menu and the entity component using an event-driven approach...

// menu state
class MenuState : IHandle<KeyCommand>() {
    void Handle(KeyCommand keyCommand) {
        if(keyCommand.Key == Keys.Enter && keyCommand.IsPressed)
        ...
    }
}

// entity component
class EntityControllerComponent : IHandle<KeyCommand>() {
...
}

... the concerns are clearly separated. But what happens now if I press the ENTER key? Who decides which part of the game is allowed to actually receive and handle the event?


texts: How do I call OpenGL methods that require pointers in C#?

texts:
I have found the following C++ code in this tutorial to draw a triangle with OpenGL 4:

float points[] = {
   0.0f,  0.5f,  0.0f,
   0.5f, -0.5f,  0.0f,
  -0.5f, -0.5f,  0.0f
};
GLuint vbo = 0;
glGenBuffers (1, &vbo);
glBindBuffer (GL_ARRAY_BUFFER, vbo);
glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (float), points, GL_STATIC_DRAW);

I use C# and OpenTK, so I tried to translate the code:

        float[] points =
        {
           0.0f,  0.5f,  0.0f,
           0.5f, -0.5f,  0.0f,
          -0.5f, -0.5f,  0.0f
        };
        uint[] vbo = {0};
        GL.GenBuffers(1, vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]);
        GL.BufferData(BufferTarget.ArrayBuffer, 9 * sizeof(float), ppoints, BufferUsageHint.StaticDraw);

The problem is that GL.GenBuffers() and GL.BufferData() require pointers (Visual Studio shows *int or out int and ref float*, IntPtr).

I've tried to fix this, but it didn't work:

        float[] points =
        {
           0.0f,  0.5f,  0.0f,
           0.5f, -0.5f,  0.0f,
          -0.5f, -0.5f,  0.0f
        };
        uint[] vbo = {0};
        GL.GenBuffers(1, vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]);

        unsafe
        {
            fixed (float* ppoints = points)
            {
                GL.BufferData(BufferTarget.ArrayBuffer, 9 * sizeof(float), ppoints, BufferUsageHint.StaticDraw);
            }
        }

So my question is how to use these methods in a good C# style?


texts: GLSL C++ Only first sampler array index is accessible

texts:
I have the following shader, which whose fragment shader contains a sampler array of 16 elements.

Fragment

#version 330 core
in vec2 _uv;
flat in int _instanceID;

out vec4 color;

uniform sampler2D sampler[16];

void main() {
    color = texture(sampler[_instanceID], _uv);
}

Now when I try to set the second array element using the following method

void Shader::setUniform(const std::string& uniform, GLuint* values, size_t amount) const {
    bindProgram();

    GLuint loc = getUniformLocation(uniform + "[0]");
    for(int i = 0; i < amount; i++){
        glUniform1ui(loc+i, values[i]);
        std::cout << values[i] << " "; //For debug
    }
    std::cout << std::endl; //For debug
}

It just sets the first element of the shader. Even though I'm passing 2 values.

This is the output of the cout's:

5 4
5 4
5 4
5 4
...

Looking up the shader variables with GDebugger, only the first element is set.

It also only draws the first (index 0) image.


texts: Unity3D Orbit around orbiting object (transform.RotateAround)

texts:
The best way to explain this is I'm attempting to make a small model solar system (not to scale or anything complicated, just simple rotation as a learning exercise). There's a sun, a planet, and that planet's moon. The planet orbits like normal, however the moon orbiting around the planet shoots off and makes an extremely large and far-away orbit.

My code is as follows (where "target" is the object being orbited around, and "transform"  is the orbiting object itself. Both are "Transform" objects.):

public class RotateAndOrbit : MonoBehaviour {
    public Transform target;
    public float RotationSpeed = 100f;
    public float OrbitDegrees = 1f;
    void Update () {
       transform.Rotate(Vector3.up, RotationSpeed * Time.deltaTime);
       transform.RotateAround(target.position, Vector3.up, OrbitDegrees);
    }
}

I'm not sure how to compensate for this or even what my mistake is called, but any help would be appreciated.


texts: How to calculate gravity with multiple bodies?

texts:
I'm looking at building something space-related, and trying to figure out how realistic gravity calculations would work.

The specific question I want to answer is, if I have a sun and an arbitrary number of planets in the system, and I know what the position and mass of each of them is, and I have a spaceship at position P trying to accelerate in direction D, how much thrust would that require if the same acceleration in purely gravitically "flat" space would require 1 unit of thrust?

For the sake of simplicity, assume that the entire solar system exists in a 2-dimensional plane.


texts: Getting world coordinates from mouse position

texts:
I am drawing a 2D mesh imported from CAD. The mesh vertex coordinates are in feet from some arbitrary origin and Z is always 0. I am supplying the coordinates to my shader program and using projection matrix, view matrix and model matrix to display everything. I am also using the view matrix and the model matrix to pan and zoom my 2D scene. I am trying to get the coordinates in feet from my mouse cursor coordinates. Should be a straightforward solution. A matrix multiplied by it's inverse will give you an identity matrix but something is very wrong. Here is my code (don't lough at the vb, I took over an old project):

Private Sub openGLControl1_MouseMove(sender As Object, e As MouseEventArgs) Handles openGLControl1.MouseMove
    Dim UnprojectMat As mat4 = glm.inverse(scene.projectionMatrix * scene.viewMatrix * scene.modelMatrix)
    Dim wCoordsVec As vec4 = UnprojectMat * New vec4(2 * e.X / openGLControl1.Width - 1, -(2 * e.Y / openGLControl1.Height - 1), 0, 1)
    wCoordsVec = wCoordsVec / wCoordsVec.w
    wCoordsLabel.Text = wCoordsVec.x.ToString + ", " + wCoordsVec.y.ToString
End Sub

And this is my vertex shader:

#version 150

in vec3 in_Position;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

void main(void) {
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
//pass_Color = in_Color;

}

The in_Position vector is what I'm trying to get.
As you see, I normalized the mouse coordinates for the -1, 1 coordinate system. I don't have a viewport. I'm just using the entire gl control window. Please help me pinpoint what I'm doing wrong.


texts: Flicker when drawing multiple shapes over image based texture

texts:
I'm rendering video frames with multiple color filled shapes over it using SharpDx and D3D11.

Rendering seems to be fine when just rendering the video frame and is as expected.

Now if i draw a single color filled shape it is drawn and rendered as expected.

Hoever, the problem occurs when I'm trying to render more than one color filled shapes over a video frame texture.

Apart from first  colored shape , all other shapes drawn flicker when rendered thus showing the pixels under neath which are the pixels for the rendered video frame.

Any ideas as to why does this occur ?

If any more information is required then do let me know.

P.S. Using ShaprDx and Directx11

Thanks.

Edit:
It seemed to be due to rendering the color filled shapes with the same z order as the underlying texture.

This was resolved with recommendation from another forum available here as long i'm just drawing a shape filled with color but when i'm filling the quad/shapes with textures the problem is still there.

I have also tried to set the ZOrder for the each of the shapes to be different yet the problem is still there.


texts: Label does not maintain correct position within a Table

texts:
I'm hoping the fix is quite simple, but this has become increasingly frustrating. I've built a minimally reproducable example. This is how the table is rendered:

And this is the corresponding code:

    private Table testTable() {
        Table table = new Table();
        Skin skin = new Skin(Gdx.files.internal("skin/uiskin.json"));
        Label label1 = new Label("String", skin);
        Label label2 = new Label("Hello", skin);
        Label label3 = new Label("World", skin);

        table.add(label1);

        table.row();

        table.add(label2).width(100).height(100);
        table.add(label3).width(200).height(200);

        table.setFillParent(true);
        table.debugAll();

        return table;
    }

As you can see, the "Hello" and "World" labels are not centered within their logical tables. Further, even if I try .width(100).height(100).center(), or even .bottom().right(), for example, the two labels' positions are always fixed to the left, center of their logical table.

The only way I could 'fix' the problem is by excluding the .width().height(), but I need them for my UI.

Any thoughts?


texts: How can I test if a point lies between two parallel lines?

texts:
In the game I'm designing there is a blast that shoots out from an origin point towards the direction of the mouse. The width of this blast is always going to be the same.

Along the bottom of the screen (what's currently) squares move about which should be effected by the blast that the player controls.

Currently I am trying to work out a way to discover if the corners of these squares are within the blast's two bounding lines. I thought the best way to do this would be to rotate the corners of the square around an origin point as if the blast were completely horizontal and see if the Y values of the corners were less than or equal to the width of the blast which would mean that they lie within the effected region, but I can't work out


texts: When drawing text, numbers appear as D1 or NumPad1 rather than just numbers

texts:
Been writing a class for a main menu, there's a play button and when pressed it goes to a window that asks for coordinates, sadly when writing with the keys and using the numbers the output is either D1, D2, D3... and so on, or NumPad1, NumPad2... and such. What I want is for the output to be just the number itself rather than the key name.

    private string Coordinates = string.Empty;
    private SpriteFont font;

    private Keys[] lastPressedKeys = new Keys[5];
    public void GetKeys()
    {
        KeyboardState kbState = Keyboard.GetState();

        Keys[] pressedKeys = kbState.GetPressedKeys();

        foreach (Keys key in lastPressedKeys)
        {
            if (!pressedKeys.Contains(key))
            {
                //key is no longer pressed
                OnKeyUp(key);
            }

        }
        foreach (Keys key in pressedKeys)
        {
            if (!lastPressedKeys.Contains(key))
            {
                OnKeyDown(key);
            }
        }
        lastPressedKeys = pressedKeys;
    }
    public void OnKeyUp(Keys key)
    {

    }

    public void OnKeyDown(Keys key)
    {
        KeyboardState kbState = Keyboard.GetState();

        if (key == Keys.Back && Coordinates.Length > 0)
        {
            Coordinates = Coordinates.Remove(Coordinates.Length - 1);
        }
        else
        {

            Coordinates += key.ToString();

        }

    }

Here's the whole class
https://pastebin.com/ZJqXx0zc

is there something wrong with using ToString? Or should I be using something different for numbers?


texts:
I'm making a map generation script which generates different biomes: "land", "beach", "ocean" using perlin noise but the problem is that each biomes is at different heights for example i use

height = (int)PerlinNoise (seed,x,90,10,15); //for land
height = (int)PerlinNoise (seed,x,70,10,5); //for beach
height = (int)PerlinNoise (seed,x,20,10,35); //for ocean

This is the method:

float PerlinNoise( int seed, float x, float height, float scale, float roughness){
    Vector2 originPoint = new Vector2 ((seed + mapSize.x / 2) * roughness / mapSize.x, 0);

    float xCoord = (seed + x) * roughness / mapSize.x;

    return (Mathf.PerlinNoise (xCoord, 0) * scale) + height;
}

But my problem is merging between biomes, when i generate the terrain each biome just jumps down/up to the required height how can i fix this? I've tried using a lerp function but the map is generated left-right. Is there a way i can implement this in the PerlinNoise method so that if i supply the previous height and a weight it returns the next height as if the biomes where going to merge.


texts: How can I access a method on a child elements script in Unity?

texts:
I'm using Unity.  I have an empty elements called GameElements which I programmatically add child elements to (players can spawn these objects themselves in-game).

Within my script Play.cs I have a method to handle the onclick event when someone clicks the Play image/button.  I want to run through all of the child elements of my GameElements object and run the method on the script Circle.cs which is attached to those child elements.

Here is my Play.cs:

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

public class Play : MonoBehaviour
{
    public GameObject GameElements;
    public Circle CircleScript;

    public void OnMouseDown()
    {
        Debug.Log("Clicked!", gameObject);

        GameElements = GameObject.Find("GameElements");

        // Loop through game objects and init them
        Transform[] allChildren = GameElements.GetComponentsInChildren<Transform>();
        foreach (Transform child in allChildren) {
            // do whatever you want with child transform object here
            Debug.Log("child...", child);
            CircleScript = (Circle) child.GetComponent(typeof(Circle));
            CircleScript.Init();
        }
    }
}

The click events do generate a Debug Log in console for the child objects as expected.

However I get the following:

NullReferenceException: Object reference not set to an instance of an object
Play.OnMouseDown () (at Assets/Game/Scripts/Play.cs:22)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

Any help appreciated.


texts: How to change texture from pvr.ccz in Cocos2d?

texts:
I'm using .pvr.ccz file that texturePacker application created for me , I created a Sprite that it's image choosed from this file(.pvr.ccz) like below:

  CCSprite *mySprite = CCSprite::createWithSpriteFrameName("first.png");

But how can I change it's texture using .pvr.ccz file?

I knew below solution for changing texture of a sprite, but it works when second.png file is normal PNG file and is not compressed in a.pvr.ccz file.

mySprite->setTexture(CCTextureCache::sharedTextureCache()->addImage("second.png"));


texts:
i developing side Scrolling endless Game. i want to Change X Axis of camera as player moving to Right. and i almost Done That. but the problem is when move Camera to the Right then its look so stiff in Android Device not Move Smooth.
That's the code I Write in  my Script to move Camera when player move.

public static float offsetX;

void Update () {

    if (BirdScript.instance != null) {

        if (BirdScript.instance.isAlive) {
            MoveTheCamera ();
        }
    }

}

void MoveTheCamera() {
    Vector3 temp = transform.position;
    temp.x = BirdScript.instance.GetPositionX () + offsetX;
    transform.position = temp;

}

and in my Player Script(BirdScript.cs) i also set my player Position and also Get in CameraScript

void Awake() {

   setCameraX();

}

void setCameraX() {

    CameraScript.offsetX = (Camera.main.transform.position.x - transform.position.x) - 1f;

}

public float GetPositionX(){

    return transform.position.x;
}

what should i do to move my camera smoothly in device? thanks.....


texts: How can I reference multiple XNA content projects from my game project?

texts:
I'm developing an engine in XNA and would like to have two different ContentManagers: one for the game (sprites, sounds, etc.) and one for the engine (shaders, dlls, etc.)

Right now, I have this:

using Microsoft.Xna.Framework;
....
public class Engine
{
    public ContentManager GameContent;
    public ContentManager EngineContent;
    public IServiceContainer Services = null;

    public Engine(GraphicsDeviceManager Graphics, ContentManager Content)
    {
        Services = new ServiceContainer();
        Services.AddService(typeof(IGraphicsDeviceService), Graphics);
        Services.AddService(typeof(IGraphicsDeviceManager), Graphics);
        GameContent = Content;
        EngineContent = new ContentManager(Services, "EngineContent");
        ...
    }
}

The GameContent and EngineContent projects root directories are set to GameContent and EngineContent, respectively. I have a content reference to EngineContent in the Engine project and references to both GameContent and EngineContent in the Game project.

Why can I access my GameContent but not my EngineContent?


texts: I want to create a text based game, where the player will type up,down, left or right and the sprite will move in that direction. I created the game and at the moment the player moves with the up,left,down and right keys. I would like to change the movement of the sprite from keypresses to text commands, Ive googled a lot on creating text based games in XNA but have had no luck. Could you please help me or guide me in the right direction of how to do this in XNA.


texts:
I remember back when I played runescape, they always had these really interactive holiday events. And players would be squirming all around trying to find where it was. After you would complete it (it was like a mini-quest), you would be rewarded with some kind of item. I thought it was really cool, but if you missed the event you'd be pooped out. And now days, I play simpler games, such as parallel kingdom, and they just have boring items that you can buy for holidays.

Is it worth making holiday events, or could you get by without them?


texts: Unity sprite with higher sorting layer not firing its OnMouseDown function

texts:
I have 2 objects, both have a Box collider 2D.

The first object is on the Level1 Sorting Layer and has a Tile script attached to it.

The second object is on the Level0 Sorting Layer and doesn't have any scripts.

The Tile script code is as follows:

void OnMouseDown()
{
    Debug.Log(Input.mousePosition.ToString());
}

Whenever I click the top tile, nothing prints in the console unless I click on the red area like I show in the image below (red area = [first box collider] minus [the two box colliders intersection area]).

Why this happens ? Why doesn't the OnMouseDown() function fire up simply when you click on its collider, since the top tile is on a higher sorting layer than the bottom tile. How does this work ? Doesn't sorting layer affect the 2D box collider ? (If I change the Z-axis of the top tile to -1, while keeping the bottom tile to 0, it works as expected.)


texts: When someone joins or leaves a room, send the entire user list or just the delta?

texts:
I'm developing a game that has a lot of rooms and most rooms will have between 2 and 15 users. On the UI there is a list of all the players currently in the room. I'm wondering, when someone joins a room, should the server send the entire list of players (admittedly not much) to everyone, or just the delta?

Option 1) Send the entire list to the new person joining because he needs all of them and send the one user to the rest of the players because they already know who else is in the room. Possible synchronization issues and harder to code.

Option 2) When someone enters or leaves a room, resend the entire list of players to everyone. No synchronization issues, much easier to code and test, but increased packet sizes.

Which option would you choose or is there a third one? For reference I'm using node.js and socket.io.


texts:
We, as in my 4 person indie group, have an entire whiteboard that looks like graffiti for prototyping our game ideas. We look at it every day and choose which idea draws us in the most when we near time to start a new project. We also randomly draw characters that seem interesting even if they have no gameplay associated with them. This works but doesn't always seem to give us the best understanding of our ideas. We tried a rule that if you come up with a game idea, build a very basic prototype and show us, but that also wastes time.

So, my question is "what is a good way to prototype game ideas". We need a balance between getting the idea across and not skipping it because we don't understand it, but also not wasting time building up a ton of ideas that will never be touched. What is an efficient way to describe the major aspects like gameplay, art feel, special features, audience, etc.


texts: How does directX API implement supersampling in GUP layer?Does it allocate a scaled-framebuffer other than user-specified framebuffer?

texts:
For example,if I create a backbuffer of size 800 * 600 and turn on 4x-supersampling, is it the case that the graphics driver actually allocates a backbuffer of size 3200 * 2400 under the hood then downsamples to samller buffer?
PS:3200 calculated from 800 * 4,   2400 calculated from 600 * 4


texts: How to run JarSplice from the command line?

texts:
I've tried java -jar jarsplice.jar --help and "" /? which just launches the UI. I'd like my game to automatically be packaged into a single jar when it's built so it would be very useful to be able to call it from the command line.

e.g-

java -jar jarsplice.jar -jars "..." -natives "..." -output "..." -exe -sh -mac


texts: Memory leak while loading libgdx game screen

texts: So, I have a lot of texture atlases in my code for a talking tom type libgdx, and I use around 6 of them per screen. The app crashes abruptly without any errors on devices with 1gb ram or less. I started profiling my code and found that I have 3500+ texture bindings, how should i minimize these?


texts: Deserialize inherited classes into the same list in XNA

texts:
I am writing a Gui for a game (for what else ...).
Therefor I wrote a class GuiElement which has some serializeable fields. From this class I deflect a Class "Button" which has one serializeable field more.
Furthermore, I have a Class GuiWindow, which is as well deflected from "GuiElement".
An Object of this Class has a Field "HandledElements" of the type "List". To know the layout of the Menues, I use XML-Files, which look like that (for example):

<?xml version="1.0" encoding="utf-8" ?>
<XnaContent xmlns:Generic="System.Collections.Generic">
 <Asset Type="System.Collections.Generic.List[GUI.GuiWindow]">
  <Item>
   <Position>0 0</Position>
   <AlternativeImagePath></AlternativeImagePath>
   <IsActive>true</IsActive>
   <Name>MainMenu</Name>
   <HandledElements>
    <Item>
      <Position>100 100</Position>
      <AlternativeImagePath></AlternativeImagePath>
      <IsActive>true</IsActive>
      <Name>Optionen</Name>
      <Caption>Optionen</Caption>
    </Item>
   </HandledElements>
 </Item>

  <Item>
   <Position>0 0</Position>
   <AlternativeImagePath></AlternativeImagePath>
   <IsActive>false</IsActive>
   <Name>Options</Name>
   <HandledElements>
   </HandledElements>
  </Item>
 </Asset>
</XnaContent>

As you can see, the first window has in its "HandledElements" List an Item with the Field . This is a field which only a Button has. The Problem is now: I can't deserialize this XML file, because GuiElement does not have this Field, it only has the few fields above.
I thought it would know automatically which Class to use,but it doesn't.
Do I really have to give my windows a list for each child class of GuiElement?
Or can I do another workaround?


texts: What's the "right way" to open a websocket connection inside WebGL?

texts:
The official Unity documentation says that, to run websockets in the WebGL player, you should use this plugin on the Asset Store.  Unfortunately, following that link leads to a notice that this asset has been deprecated and is no longer available, with no explanation as to why or what should be done to replace it.

With that unavailable, how should I implement WebGL websockets in my game?


texts:
I'm using a line renderer as a laser aim for my character. If the aim hits an object it ends at that object. If the aim doesn't hit an object it continues a predefined distance.

If I aim at an object it works fine, if I stand behind the object it also works, but if I stand in front of it, the line is rendered behind the object creating the illussion that the character stands behind the object.

If I change the sorting order for the line I can make it to be in front of the object, but this is a bit tedious because then it will be in front of this object when it is in fact behind it.

In the screenshot below a line is drawn from the picked up C4 which is in front of the pillar, but the line is drawn behind the pillar.

Is there any way to solve this issue with a line renderer? I've been thinking of just using a cube and stretch it instead.

Thanks in advance!

Update 1: I made a cube-solution instead, but soon realized that the issue is with a shader that is set to fade/transparent and that this is due to sorting order. How can I dynamically change the sorting order in code so that my moving transparent object always appear in the correct place?

Update 2: I noticed that my own answer below isn't working 100%. It works for most scenarios but if I'm standing at origo and aiming behind a pillar the sight is rendered in front of the pillar. In the image below it is clearly visible from the top view that I'm aiming behind the pillar. (This is done with a deformed cube, the line renderer had even more issues).


texts: How to use Kobold2D/Cocos2D to create a turn-based iOS 5 Game Center game?

texts: I've searched for information on this, but cannot find it, is this not something you can do yet with Kobold2D/Cocos2D? or are there options I've missed?


texts: How is game development different from other software development?

texts:
For a solid general purpose software developer, what specifically is different about game development, either fundamentally or just differences in degree?

I've done toy games like Tic-tac-toe, Tetris, and a brute-force sudoku solver (with UI) and I'm now embarking on a mid-sized project (mid-sized for being a single developer and not having done many games) and one thing I've found with this particular project is that separation of concerns is a lot harder since everything affects state, and every object can interact with every other object in a myriad of ways.

So far I've managed to keep the code reasonably clean for my satisfaction but I find that keeping clean code in non-trivial games is a lot harder than it is for my day job.

The game I'm working on is turn-based and the graphics are going to be fairly simple (web-based, mostly through DOM manipulation) so real time and 3d work aren't really applicable to me, but I'd still be interested in answers regarding those if they're interesting.  Mostly interested in general game logic though.

P.S. Feel free to retag this, I'm not really sure what tags are applicable.


texts: Unity Anima2D - IK Limb for leg not working

texts:
I'm having an issue getting an IK limb to work using Anima2D in Unity. If I place a limb IK for the neck joint, the head moves as expected, however trying to place one for the leg seems to have no effect.

A CCD IK seems to work, but only moving one bone of the leg, whereas I need both bones to move, like a real limb with a knee joint.

Is there anything obvious I'm doing wrong?

Thanks!


texts: Self-righting agents that have fallen over

texts:
I need insect-like agents that have fallen/rolled on their back/side to naturally re-orient themselves.  The agents are modeled as simple cuboids in the physics engine (Bullet) to approximate an ant-like shape.

At the moment I correct the orientation by instantly altering it when the dot product of surface 'up' and agent 'up' is less than some number (e.g. -0.5).  Thus the agents can fall over only so much before they are insta-righted in the blink of an eye.

Obviously this looks nasty. Plus in the border cases, where the dot product isn't quite low enough, they can still fall over and don't get self-righted.

So, I need a way to have the critters automatically roll back onto their feet. How can I do this? The way I see it there are two problems:

1) How to determine the best rotation axis (e.g. better to roll on their back than head-to-tail)?

2) How to work out the magnitude of torque required to overcome the physics engine, whilst not being too much that has them flipping end over end?

[Full disclosure: I originally posted this question on gamedev.net, to no response.  I also posted in StackOverflow, but deleted the post when this stackexchange was recommended instead]


texts:
I'm making a camera which tracks the player. I am using a basic algorithm to calculate a position for the camera relative to the player. Then I am taking an average of this over the last x number of frames. This creates a nice chase camera which always slightly lags and evens out the players movements.

Where I am running into trouble is with delta Time. How can I weight each entry in my list of previous positions so that delta time is taken into account. Currently I'm having an issue where, when the frame rate is particularly slow, the camera lags really far behind the player.

I should also mention that currently I am adding each entry ElapsedTimeInSeconds/0.01f times to give the weight. So the average is effectively over fewer frames if the frame rate is slow. I also tried entering values as Value * DeltaTime, then keeping an average of delta time to divide the values by when I get them back out of my average tracking class but that didn't work.

What I think I really want is an average over the last n seconds rather than the last n frames.


texts: I'm trying to create a texture atlas where each triangle face is laid separately from each other (i.e. it is not typical mesh parameterization). In order to do this, I would have to pack the triangles into a 2D texture image. Can someone suggest a good algorithm to do this efficiently, both timely and spatially?


texts: Split a 2D scene in layers or have a z coordinate

texts:
I am in the process of writing a 2D game engine, and a dilemma emerged. Let me explain the situation...

I have a Scene class, to which various objects can be added (Drawable, ParticleEmitter, Light2D, etc), and as this is a 2D scene, things will obviously be drawn over each other.

My first thought was that I could have basic add and remove methods, but I soon realized that then there would be no way for the programmer to control the order in which things were drawn.

So I can up with two options, each with its pros and cons.

A) Would be to split the scene in layers. By that I mean instead of having the scene be a container of objects, have it be a container of layers, which are in turn the containers of objects.

B) Would require to have some kind of z-coordinate, and then have the scene sorted so objects with lower z get drawn first.

Option A is pretty solid, but the problem is with the lights. In what layer do I add it? Does it work cross-layer? On all bottom layers? And I still need the Z coordinate to calculate the shadow!

Option B would require me to change all my code from having Vector2D positions, to some kind of class that inherits from Vector2D and adds a z coordinate to it (I don't want it to be a Vector3D because I still need all the same methods the 2D kind has, just with .z clamped on).

Am I missing something? Is there an alternative to these methods?

I'm working in Javascript, if that makes a difference.

Edit: it was hard to decide with which option should I go, but I chose option B, adding the z coordinate. Some other design choices that might help others reading this question:

The actual map is a 2D space, and therefor, all positions should be Vector2D instances. But, as I also need a third coordinate, I made a new class, called ScenePosition, which inherits from Vector2D and just adds a z option. What was crucial was to keep the methods thinking that they are still operating on a Vector2D instance.
There is no way that sorting the scene by the z axis on every frame would be efficient, so watch out when adding things to the scene. For example: you would add a 4 at the end of this list, not the beginning: [1, 2, 3].
I chose to have a changedOrder property on the Scene, which you set to true when you change the z coordinate of some object. Then, the array is sorted before rendering, and changedOrder is set to true.


texts:
I'm currenlty working on an assignment and would appreciate any sort of help on the following implementation

The question follows

We are tasked to  implement some heuristics but one of them is really confusing to me.

  The following are a set of heuristics widely used by game developers
  for the movement of human characters while trying to reach a target

  A. If the character is stationary or moving very slowly

  If it is a very small distance from its target, it will step there directly, even if this involves moving backward or sidestepping
  Else if the target is farther away, the character will first turn on the spot to face its target and then move forward to reach it.

  B. Else if the character is moving with some speed

  If the target is within a speed-dependent arc (like a narrow perception zone, or a cone of perception) in front of it, then it will
  continue to move forward but add a rotational component to
  incrementally turn toward the target**
  Else if the target is outside its arc, then it will stop moving and change direction on the spot before setting off once more.

B2 I'm not entirely sure what a speed dependent arc is. I googled it and it bring it back to the textbook( Artificial Intelligence for video games). My question is : what is a speed dependent arc?


texts: Can I legally sell an XNA game made with Visual C# Express Edition?

texts:
I've dowloaded Visual C# Express Edition and when it starts up it says "for evaluation purposes only." What does this mean?

Does this mean I have to buy the full version to legally sell my game I make with it? Or can I just use the free express edition? I really dont want to make a game and then find out I can't sell it.


texts: Using Euler angles to rotate object 360 degrees

texts:
I'm trying to create script that rotates object in given axis by set amount of degrees.
That's my 2 core methods
public Vector3 rotation;

public void RotateDegreesFast ()
{
    transform.DOLocalRotate (GetTargetRotation (), rotationTime);
}

private Vector3 GetTargetRotation ()
{
    Vector3 newRotation = new Vector3 (
        rotation.x + transform.localEulerAngles.x,
        rotation.y + transform.localEulerAngles.y,
        rotation.z + transform.localEulerAngles.z)

    return newRotation;
}

I was using this script for a little while, it was working perfectly in Y and Z axis. Now I try to rotate object 45 degrees in X axis (rotation = new Vector3(45f, 0f, 0f)). It works until rotation in x value equals 135. Transform.localEulerAngles.x is returning 45 instead of 135. So it's stuck between 90 and 135 degrees. I was trying to use transform.localRotation.eulerAngles.x instead, but it doesn't work as well.
I am aware this works that way because specific Euler angle can be represented in many ways. I also know that DOTween has DOLocalRotateQuaternion method, but the thing is that this component is often reused by a designer that sets value of rotation variable in the inspector. It's way easier to use Euler angles for him.


texts: Restarting a libGDX game to apply changes to resolution

texts:
How can I restart a LibGDX game to apply certain changes to the game such as changes to the resolution (going from 1920X1080 to 1280X720), or changing full screen.
Granted the resize(int width, int height) can help with the resolution change, but I need to change other settings as well so I rather restart the game and continue from the options menu instead of forcing the user to manually exit the game and then restart it.


texts: Looking for an elegant way to represent fixed parts of a randomly generated level map

texts:
I'm coding from scratch a small experimental game on a medium-sized random rectangular square tile map. (Say, a map of a dungeon.)

There are several types of tiles (for example: floor, wall, monster, boss, treasure, player etc.). There are no extra information stored in the map tiles, just tile type.

Most parts of map are randomly generated. However there are several features that are to appear on every generated map in pre-set places. Say, walls around the dungeon, boss locations, player spawn point and the treasure.

Note: Since the game is small, coded for fun, and the only game designer is a programmer (that is, me myself), I do not plan to spend resources on coding a level editor or supporting an existing one. Also, I do not plan to support existing tile map libraries as I want to dig into some of the related coding problems myself (see above about fun), but I be happy happily to look at relevant existing code as a reference.

When I look at my map generation code, I find it rather ugly.

Is there an elegant way to deal with the problem? If that matters, I'm writing this game in JavaScript, but I will be happy to see a relevant reference in any programming language.

Here is a partial pseudocode to illustrate how my current tile generator solution looks like:

this.init = function(w, h) {
  this.w = w;
  this.h = h;
  this.tile_presets_ = { };

  var mid_h = Math.floor(h / 2);
  var quarter_w = Math.floor(w / 4);

  /* Here is the part I don't like -- a set of generator rules: */

  this.preset_col_(0, Tile.GRASS);
  this.preset_tile_(0, mid_h, Tile.FLOOR);

  this.preset_col_(1, Tile.GRASS);
  this.preset_tile_(1, mid_h, Tile.FLOOR);

  this.preset_col_(2, Tile.WALL);
  this.preset_tile_(2, mid_h, Tile.FLOOR);

  this.preset_tile_(2, mid_h, Tile.PLAYER);

  this.preset_tile_(1 * quarter_w, mid_h, Tile.BOSS);

  this.preset_tile_(2 * quarter_w, mid_h, Tile.BOSS);

  this.preset_tile_(3 * quarter_w, mid_h_, Tile.TREASURE);

  this.preset_col_(w - 1, Tile.WALL);
};

Implementation details that may help to understand the code above:

this.tile = function(x, y) {
  var preset = this.tile_presets_[x + y * this.w];
  if (preset !== undefined) {
    return preset;
  }

  return this.random_tile_();
};

this.preset_tile_ = function(x, y, tile) {
  this.tile_presets_[x + y * this.w] = tile;
};

this.preset_col_ = function(x, tile) {
  for (var y = 0; y < this.h; ++y) {
    this.preset_tile_(x, y, tile);
  }
};

Note that I shown a rather simple set of generator rules above. Actual thing is several times longer.

I hate that the code looks imperative — and it is hard to figure out what is going on from the first glance. I think that declarative approach could help. But so far I can't figure out a good solution.

Any clues?


texts: How can we validate subjective inputs from a client?

texts:
Let's propose for a minute where we have a game using something like the Virtuix Omni. You track feet movement. You track the speed at which they run. Now, let's suppose we want to translate this into game movement and velocity relative to the speed the player is moving. Now, suppose the game is multiplayer. How can a server validate that the input is reasonable?
Most architectures described often tell us to validate the input - but in this case we truly want the player to tell us how fast they're running.

How can I we ensure sane values and not some hacked "always turbo" device?


texts: Determining the location of installed/on disk game assets

texts:
I've been thinking a lot about the best way to store and load assets in your filesystem.  By this I mean where in the file system to store them, and how to retrieve them when loading etc., as opposed to how their stored when the program is actually running.  I would imagine that this would be a fairly common question, but I can't seem to find it anywhere else, perhaps because I'm not asking it properly.

So far, I have found two strategies, and I would like to know what other ones there are.

Storing the assets in an absolute path on the system.  You may have to get the users home directory if the user doesn't need to be an admit/root to install the game, and other OS dependant stuff would probably need to be done to ensure that the path is actually valid, but it seems like this could work well.
Get the game's location on the system, and assume that assets can be found in an adjacent directory.  I don't think there is any OS independent way to do this, but it does seem feasible.  This might be nice as it doesn't require the user to install the game, making it all around more portable, but it does seem like it would destroy an OS paradigm where specific portions of the game when in a certain place in the os (say /usr/games, and the executable would go in a different directory).

Both of these ways do seem a bit clunky, so are there any other ways to get the location of your assets?  Otherwise, which is used more in games you've worked on?  Thank you.


texts:
I have some experience in developing all sorts of (small) games using Unity3D, I have a few personal game projects and I also work for a small game studio. The only subject in game development that I've avoided at all costs was AI, up until now. My other projects required just basic NPC algorithms, so i can't call that AI.
On to my problem: I have 2 or more player opponents that have to shoot at each other, taking turns (think of a Worms game). They fire using a ballistic arc, adjusting firing power and gun elevation. The problem is making the CPU player to behave like a human player would, without using firing at random. I have, from other games, and algorithm that computes the angle and projectile velocity required to hit dead-on the target, but that would kill the opponent in the first few seconds. So i need a smarter, human like approach: fire a trial shot, smartly adjust to improve aim. Also account for wind direction and speed that affect the projectile.

After some AI research, I was thinking of using genetic algorithms, but i do not need a perfect solution to my problem (to hit the target in the first round) but rather a constant improving one. Also if the algorithm could be tuned for easy/medium/hard difficulty would be great. I do not necessarily need a complete solution, but a direction to dig to.