texts: Use Accelerometer for Roll-a-ball Movement

texts:
I'm working on maze game for Android in Unity 5.1.1f1 and I have troubles with controlling my ball with accelerometer. At start I tried:

public class PlayerController : MonoBehaviour {

    public GameObject sphere;
    public Camera camera;
    public float speed=200;

    private Rigidbody myRigidBody;

    void Start()
    {
        myRigidBody = gameObject.GetComponent<Rigidbody> ();
    }

    void FixedUpdate()
    {
        float moveH = Input.acceleration.x;
        float moveV = -Input.acceleration.z;

        Vector3 move = new Vector3 (moveH, 0.0f, moveV);
        myRigidBody.AddForce (move * speed*Time.deltaTime);
    }
}

But the ball is not moving as it should. Then I tried another solution. But my ball still doesn't move right. It seems like it's sometimes hard to move left/right/forward/backward, also it's possible my ball will rotate in the opposite direction.

public class PlayerController : MonoBehaviour {

    public float speedAc = 10;

    //accelerometer
    private Vector3 zeroAc;
    private Vector3 curAc;
    private float sensH = 10;
    private float sensV = 10;
    private float smooth = 0.5f;
    private float GetAxisH = 0;
    private float GetAxisV = 0;

    // Use this for initialization
    void Start () {

        ResetAxes();
    }

    //accelerometer
    void ResetAxes(){
        zeroAc = Input.acceleration;
        curAc = Vector3.zero;
    }

    void FixedUpdate () {

        curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);

        GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
        GetAxisV = Mathf.Clamp(-curAc.z * sensV, -1, 1);

        Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
        GetComponent<Rigidbody>().AddForce(movement * speedAc);
    }
}

Can someone help me, please?


texts: Random lines drawn on screen while all vertexes are correct

texts:
I'm writing a 2D program in which a monocycle follows a Catmull-Rom spline. My problem is when I write the circle, the drawing goes crazy. There is one line on the screenshot (which seems to be 3 when watching it), that rotates with the circle and blinks around it.

It doesn't happen always, comes randomly, sometimes it's fine then it will start this after a few seconds.

I have no clue what could cause it. My calculations are correct, there aren't fauly or nans/inf-s in the array, and if I put printf right before buffering the vbo, the lines don't appear, so I can't even debug it. And sometimes there's a small blinking in the green part too.

Here's some part of my code.

Creating the curve:

void Create() {
    // Curve
    glGenVertexArrays(1, &vaoCurve);
    glBindVertexArray(vaoCurve);

    glGenBuffers(1, &vboCurve); // Generate 1 vertex buffer object
    glBindBuffer(GL_ARRAY_BUFFER, vboCurve);
    // Enable the vertex attribute arrays
    glEnableVertexAttribArray(0);  // attribute array 0
    // Map attribute array 0 to the vertex data of the interleaved vbo
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), NULL); // attribute array, components/attribute, component type, normalize?, stride, offset
}

void Create() {
    glGenVertexArrays(1, &vaoCyclist);
    glBindVertexArray(vaoCyclist);
    // Curve
    glGenBuffers(1, &vboCyclist); // Generate 1 vertex buffer object
    glBindBuffer(GL_ARRAY_BUFFER, vboCyclist);
    glGenBuffers(1, &vboHuman); // Generate 1 vertex buffer object
    // Enable the vertex attribute arrays
    glEnableVertexAttribArray(0);  // attribute array 0
    // Map attribute array 0 to the vertex data of the interleaved vbo
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), NULL); // attribute array, components/attribute, component type, normalize?, stride, offset
}

Calculating:

humanData.clear();
        circleData.clear();

        for (int i = 0; i < 180; i++) {
            cordX = cosf((float)M_PI * i * 2 / 180.0f);
            cordY = sinf((float)M_PI * i * 2 / 180.0f);

            if (i == 0) {
                circleData.push_back(cordX);
                circleData.push_back(cordY);
            }

            else if (i == 179)
            {
                circleData.push_back(cosf((float)M_PI * i * 2 / 180.0f));
                circleData.push_back(sinf((float)M_PI * i * 2 / 180.0f));

                circleData.push_back(cosf((float)M_PI * i * 2 / 180.0f));
                circleData.push_back(sinf((float)M_PI * i * 2 / 180.0f));

                circleData.push_back(cosf((float)M_PI * 0 * 2 / 180.0f));
                circleData.push_back(sinf((float)M_PI * 0 * 2 / 180.0f));
            }

            else {
                circleData.push_back(cordX);
                circleData.push_back(cordY);
                circleData.push_back(cordX);
                circleData.push_back(cordY);
            }
        }

Draw:

mat4 MVPTransform = MrotateTranslate() * camera.V() * camera.P();

MVPTransform.SetUniform(gpuProgram.getId(), "MVP");

int colorLocation = glGetUniformLocation(gpuProgram.getId(), "color");

for (int i = 0; i < circleData.size() - 1; i++)
    printf("%f\n", circleData[i]);

glBindVertexArray(vaoCyclist);
glBindBuffer(GL_ARRAY_BUFFER, vboCyclist);
glBufferData(GL_ARRAY_BUFFER, circleData.size()* sizeof(float), &circleData[0], GL_DYNAMIC_DRAW);
if (colorLocation >= 0) glUniform4f(colorLocation, 0.72f, 0.16f, 0.0f, 1.0f);
glDrawArrays(GL_LINES, 0, circleData.size());

Cyclist attributes:

class Cyclist {
private:
    unsigned int vaoCyclist, vboCyclist;
    unsigned int vboHuman;
    float r= 1;
    float v = 0;
    vec2 wTranslate = vec2(-10.0f, 0.0f);
    vec2 position = vec2(0, 0);
    float sina, fi=0, ds;
    float cordX, cordY;
    vector<float> circleData;
    vector<float> humanData;
    float dir = 1.0f;


texts: I've been considering moving to a more component-based approach in my games. Does anyone else have any decent reference material or sample implementations that would help make this transition a little easier?


texts: Unity - Access to svPosition in fragment shader

texts:
I am trying to access to the svPosition in my fragment program in Unity but I keep having this error.

  invalid input semantic 'POSITION': Legal indices are in [1,15] invalid ps_3_0 input semantic 'POSITION'

Here are some information about my whole shader.

struct : float4 pos : SV_POSITION;
vertex : o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
fragment : col.rgb = i.pos.xyz;

Any idea how to access this value?


texts: How to make a really high performance like factorio in SDL2?

texts:
i tried to make a 2D game engine for my game, used SDL2 as framework, C++ as language, and MSVC as compiler, using the graphics api and accelarated renderer. However, this still not enough. The game, at 300 objects. (Object being a simple struct holding position and SDL_Texture, and also SDL_Rect) runs smoothly at 60FPS. While suddenly goes down to around 30 at 700 objects. Each object runs SDL_RenderCopy individually, using their pointer to the texture, and individual SDL_Rect for srcrect and another one for their position in the world. I've been searching for a while and couldn't find anything useful about sprite batching in SDL2. But I heard liballegro has this feature.
My goal is to reach the performance of Factorio, rendering a huge, animated tilemap, with thousands of objects(a.k.a items, or alliens). Hence this is why I chose C++ as the language. I've been using engine like Unity and GameMaker, the game i want to port is here.
I drew every objects in a for loop like this:
for (GameObject* obj : objects) {
        obj->render();
}

Is there even any kind of sprite batching in SDL2? Should I switch to Allegro? Or is there any better frameworks for my kind of problems and needs? Thanks in advance.


texts: Point Sprite Size and Coloring OpenGL ES 2.0

texts:
I am trying to render point sprites with with variable color, but they are all black. Before I added gl_PointSize = 5.0 they had color.

The environment is Android with C++, I believe OpenGL ES 2.0.

I have tried to work from point sprite size and applying color to point sprite, but have had no luck.

Vertex Shader:

precision mediump float;
precision mediump int;
attribute vec4 vertex;
uniform mat4 mvp;
varying vec4 v_color;
void main() {
  gl_Position = mvp*vertex;
  v_color = vertex;
  gl_PointSize = 5.0;
}

Fragment Shader:

precision mediump float;
precision mediump int;
varying vec4 v_color;
uniform sampler2D tex;
void main() {
  //gl_FragColor = vec4(v_color);
  //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  //gl_FragColor = texture2D(tex, gl_PointCoord);
  gl_FragColor = vec4(v_color.rgb, texture2D(tex, gl_PointCoord).a);
}

All of the gl_FragColor assignments both commented and active lead to black points.

How do I give these points color?


texts:
I'm trying to get a basic shader to work in XNA. I pass in a bool value called "TextureEnabled" to indicate whether or not it should expect some UV texture coordinates. But regardless of what I pass, it is always expecting the UV value, and it throws and InvalidOperationException -"TextureCoordinate0 is missing":

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;

float4 worldPosition = mul(input.Position, World);
float4x4 viewProjection = mul(View, Projection);
output.Position = mul(worldPosition, viewProjection);

if (TextureEnabled == true)
{
    output.UV = input.UV; //**// always executes**
}
else
{
    output.UV = float2(1, 0);
}

return output;

}

Here's the declaration at the top of the effect file:

float4x4 World;
float4x4 View;
float4x4 Projection;
texture BasicTexture;
bool TextureEnabled = false;

I'm even setting the effect parameter in my XNA Draw() method:

paramName = "TextureEnabled";
effect.Parameters[paramName].SetValue(false);

If I just hard-code output.UV = float2(1, 0) instead of output.UV = input.UV, it does not throw an exception, so I know that has to be the problem. Its almost like the TextureEnabled variable isn't getting set up (or not evaluated), even though I can see SetValue(false) being called in the debugger. What am I doing wrong?

Here's the relevant source files, if needed: http://www.mediafire.com/?g85tc5d9582vs8g


texts: Why does my game loop speed vary on different platforms with the same hardware?

texts:
I've got a serious issue with my game loop. This loop varies in time with the platform and with the same hardware. This is a list of FPS achieved:

  -  Windows       ======= 140 to 150
  -  Linux         ======= 120 to 125
  -  Windows(WINE) ======= 125 to 135

And since my game loop is fixed timestep, the speed of the game is
not stable. Here's my game loop.

public final void run() {
    // Initialize the resources
    Map.initMap();
    initResources();
    // Start the timer
    GTimer.startTimer();
    GTimer.refresh();
    long elapsedTime = 0;
    // The game loop
    while (running) {
        // Update the game
        update(elapsedTime);
        if (state == GameState.GAME_PLAYING) {
            Map.updateObjects(elapsedTime);
        }
        // Show or hide the cursor
        if (Global.HIDE_CURSOR) {
            setCursor(GInput.INVISIBLE_CURSOR);
        } else {
            setCursor(Cursor.getDefaultCursor());
        }
        // Repaint the game and sync
        repaint();
        elapsedTime = GTimer.sync();
        Toolkit.getDefaultToolkit().sync();
    }
}

The timer package

How could I improve it?


texts: Converting time of day into a smooth day/night variable?

texts:
I'm trying to make a smooth day/night cycle for a game project that I've been working on. I've already set up a clock that adds deltaTime to seconds, wraps seconds to gameMinutes, etc. The issue that I'm having is that I want a signed normalized float to represent day (+1) and night (-1), and I'm not exactly sure what the most effective way of doing that is.

Here's my time class in pseudocode:

class GameTime {

    float snDayNight; //signed normalized

    float seconds;
    int gameMinutes;
    int gameHours;
    int gameDays;
    int gameMonths;

    //Omitted consts used for wrapping (SEC_PER_MIN, HR_PER_DAY, etc.)..

    //Per-frame update..
    public void Update(){
        seconds += Timer.GetDeltaTime();
        WrapTimeValues (); //Wraps sec to min, min to hr, etc.
        UpdateDayNightCycle ();
    }

    private void UpdateDayNightCycle(){
        //?????
    }

    //...//
}

So, my GameTime has been tested and seems to be working fine; when the value in seconds is >= the value of SEC_PER_MIN it adds another minute and stores the leftover fraction of a second. It then goes on to check minutes, hours, days, etc.

I've been a little bit stuck at UpdateDayNightCycle() though. I want to be able to convert my time into a smooth decimal value where -1 represents absolute night and 1 represents absolute day. I've normalized values between 0~1 and -1~1 before, but I've never tried to use a normalized value to represent a repeating/periodic value like night~day before..

I tried drawing a simple graph where time of day is on the x-axis and daynight value is on the y-axis. What I get is essentially a graph of a triangle wave. Sadly my math skills are a little bit underdeveloped and even after looking into formulas for triangle waves, I've been having trouble implementing it in my code..

So, am I even on the right track? How can I smoothly convert my game world's time into a single decimal value between -1 and 1?


texts: How to manage ammo when firing and reloading

texts:
I have this script and I need to fix one thing which is count correctly the number of bullets I have.

public GameObject ebullet;
public Transform Bullet_position, target;

public int ammo = 200;
public int ammo_Hold = 600;
public bool reload = false;
public bool readyToShoot;

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

    if (ammo == 0)
    {
        ammo_Hold = ammo_Hold - 200;
        ammo = 200;
    }

    if (reload == true && ammo_Hold >=0)
    {
        ammo_Hold = ammo_Hold - ammo;
        reload = false;
    }

    if (readyToShoot == true)
    {

        Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 5.0f);

        GameObject bullets = Instantiate(ebullet) as GameObject;
        bullets.transform.position = Bullet_position.transform.position * 1;
        Rigidbody rb = bullets.GetComponent<Rigidbody>();
        rb.velocity = transform.forward * 100;
        Destroy(bullets, 2f);
        ammo--;

    }
    else
    {
        print("Don't Shoot");
    }

} // end update


texts: How do I handle cyclic dependencies, in an entity/components system?

texts:
I built a standard C++ entity/component system, a bit like the one from this question). Components can access other components through their associated Entity. This is usually done by getting some kind of reference/pointer once, during component initialization. For example, a Jetpack component can access a RigidBody component, and use it to apply force to the entity. Components can be removed, during a scene, but most often, they don't. Subsystems, like Renderer, PhysicsEngine, and InputManager each listen for specific types of components, and processes them during each frame.

How should these components access each other? I see several solutions, but no good ones.

These are the potential solutions:

Raw pointers: Fast, but violates the idea of RAII. How do I check, if a component is deallocated? It feels like an unsafe path.
shared_ptr: This seems to work rather safely. I can live with the fact that it is a little slow, due to reference counting; the pointers are usually only setup during initialization, anyway. What about cyclic references? If two components reference each other, they'll never be deallocated. This can be remedied by manually clearing the shared_ptrs in some kind of Component::terminate(), that is called when the component is removed from the scene. The idea of "cleaning up", manually, seems to defeat the purpose of using smart pointers in the first place. Also, making sure terminate() is called at the right time adds complexity, as I cannot use the destructor - it's never called, due to the cyclic refs.
shared_ptr and weak_ptr: Internally, in the engine, components are stored as shared_ptrs; but the outside (i.e. components) can only get weak_ptrs. The downside, here, is that all components have to call weak_ptr::lock() each time they want to access another component, which could be several times each frame. This is also true for components that use components that are known to exist throughout the entire scene, and thus don't need an existence check. Contrary to the shared_ptr solution, this performance penalty is incurred every frame, instead of only at initialization. Maybe it is worth it overall, but it just seems clumsy, and potentially very slow.
Avoiding direct access: By adding a level of indirection between components, via a message system of some sort, the problem of cyclic dependencies may never emerge in the first place. I haven't experimented with this, as it seems to be overly complicated. Could this be overly complicated?
Avoiding cyclic deps: I'm not quite sure how do it, but maybe you could just forbid cyclic shared_ptrs altogether, in some way.

Can the downside of these solutions be remedied, or are there better ways to handle cyclical dependancies in an entity/component system?


texts:
I am new to Unity and C#.
I have a script here for a card game where my card is supposed to move up and down when the pointer is hovered over the card. But when my point hovers over each card, they all move up together and not separately. They also move when they touch other UI elements, regardless of what they are. I am doing something wrong but I don't know what.

Here is my code:

//My Codes I needs help on.
   using UnityEngine;
   using System.Collections;
   using UnityEngine.EventSystems;

   public class Mouse_Detector_Temp : MonoBehaviour {
    public bool hovered;
    // Use this for initialization
    void Start ()
    {
        hovered = false;
    }

    // Update is called once per frame
    void Update ()
    {
        //This checks to see if you are hovered over.
        if (EventSystem.current.IsPointerOverGameObject ())
        {
            Debug.Log(gameObject);
            if (hovered == false)
            {
                transform.Translate(0,10,0);
                hovered = true;
            }
        }
        else
        {
            if (hovered == true)
            {
                transform.Translate(0,-10,0);
                hovered = false;
            }
        }
    }

}

Additional Information:
This code is run UI elements that are part of a Canvas (only way to do it, so that should be obvious).


texts:
I imagine this is a problem that gets asked quite often, but reading up on it I can't seem to get a definitive answer on how to solve it.

I've got two HLSL shaders (I've simplified them in the example to just output a colour) that require RenderTargets.  For example Blur shaders.

There are two balls spinning around a central point.  As they spin, one passes between the other and the camera occluding the other ball and vice versa.

If I render them both to the same rendertarget (using the same technique) they obviously share a depth buffer, and the depth testing happens correctly.

However, when I need to use different techniques to render each ball seperately (one ball to one rendertarget and the other ball to a different) and then try to composite them depth testing fails and they are just rendered on top of each other.

Attach is the code I'm using.  I've simplified it down a lot, but it indicates the problem I'm having.

How do I go about rendering two different objects, using two different techniques to two different rendertargets and then composite them?

DepthTesting.cs

effect.fx


texts: Write alpha channel into SurfaceFormat.Single rendertarget in XNA/HLSL

texts:
I need to initialize a rendertarget ('SurfaceFormat.Single' format) drawing sprites into it.
I would like the alpha channel of the sprite to be written into the rendertarget, so that regardless of the sprite texture, i end up with sprites silhouettes in the rendertarget. But XNA doesn't support alpha blending when using SurfaceFormat.Single, and from the pixel shader in which i handle the rendertarget for further calculations, i have all 0 readings.
I find documentation of this features to be sparse and partial, so, could anyone suggest some source where i can check the sanity of my code?


texts: Initial direction of intersection between two moving vehicles?

texts:
Possible Duplicate:
  Predicting enemy position in order to have an object lead its target

I'm working with a bit of projectile prediction for my AI and I'm looking for some ideas, any input?

If a blue vehicle is moving in a direction at a constant speed of X m/s and a stationary orange vehicle has a rocket that travels Y m/s, which initial direction would the orange vehicle have to fire the rocket for it to hit the blue vehicle at the earliest time in the future?

Thanks for reading!


texts: How can I add left and right movement to my sprite without reducing forward movement?

texts:
I've made a character sprite that moves left and right when I press A and D, and moves forward automatically. However, whenever the character moves left or right, the forward movement is greatly reduced. Does anyone know a solution?

Here is my blueprint


texts:
I have a Vector2 and want to move an object towards it...
(this vector2 is the mouse position when clicked and I made sure I get only one position when its clicked)

My initial thought was to apply

  Rigidbody2D.Addforce(my vector2)

but it acting strangely...
How can I push anything towards a point?

N.B: I wanna use physics for it.... because I want to get the pushing feel!


texts: Get highest (Y-axis) vertices from primitive d20 dice in xna

texts:
I have created a d20 dice (icosahedron) in xna and used BEPU physics to roll it. But now I'm trying to get the value from the dice after its rolled. I was thinking about looking for the 3 vertices that have the highest Y-axis coords after the dice rolled. so I could set something like this:

if (vertices[0].currentPosition.Y >= 2 && vertices[1].currentPosition.Y >= 2 && vertices[2].currentPosition.Y >= 2)
{
    diceValue = 5;
}

But how do i get the current position from the vertices? Or is there a better way to check what value is on top of the dice?


texts: Usage of standardized syntaxes in gaming: yea or nay?

texts:
TL;DR: Using CSS as an element in defining rulesets in Civ-style turn-based strategy games: Madness or just plain old insanity?

Real question:

Designing ruleset parse rules is a pain. Every single game out there seems to define its own ruleset for how rulesets are to be parsed (insofar as the game features customizable rulesets, of course).

Is it time for the game dev. community to embrace standardized synatxes for rulesets?

Is CSS a viable option for customizable games?

Example: Consider a Civ-like with customizable rulesets; how nice would it not be to be able to design rulesets as follows:

artillery:era(modern) {
  range: 2;
  sprite: url(/isophex/artillery.png);
}

artillery:era(classical) {
  range: 1;
  sprite: url(/isophex/cannon.png);
}


texts: I'm developing an augmented reality application and I'm supposed to use the ALVAR library for AR marker detection. I use Unity as the game engine and unfortunately it doesn't support C++. Is there any possible way to use the C++ library as a DLL?


texts: Is there a way to keep the mesh collider when updating objects in Unity?

texts:
I have a 3D object as an imported asset in Unity which i want to make updates to in Maya.
The asset get's updated automatically in Unity when i save the object in Maya - but not in the project hierarchy where i have placed it in the scene.

Is there a way to keep the object with it's mesh collider when the model is updated without having to re-create it in the hierarchy for every iteration?


texts: 3D Translations relative to 3D Rotations

texts:
I'm trying to program camera movement to be relative to camera rotation. (Forward is always forward, regardless of pitch, yaw, and roll)
I want to be able to move forward, backward, left, right, up, and down.

I do not want to use a matrix.

I want to use sin and cos from the standard math library.

The camera rotates on all 3 axis.
The rotation order is z(roll), y(pitch), x(yaw).
When all rotations are 0, positive z is forward, positive y is down, and positive x is left.

So far I've gotten forward and backward movement to work with:

velZ = speed * cos(rotX) * cos(rotY);
velY = speed * sin(rotY);
velX = speed * sin(-rotX) * cos(rotY);

If somebody knows how to do this or knows where I can find information on this, it would be greatly appreciated.


texts:
I'm building a game in C++ (using SDL) for a college project, I'm trying to figure out how to script events that happens when a player does something, or some time passes etc.

I have a and idea of how to do it but I don't want to go against how it's commonly done.

Right now I have a class called Obj from where enemies, items and the player are child classes, my idea is to add 3 public variables to it like this:

class Obj{
    int eventDeath,eventTouch,eventTalk,eventMeet;
}

Then I could create an Obj with eventDeath=1 and when it died it would fire event(1). event() would be something like this:

void event(int n){
   switch(n){
   case 1:
      dialog("I'm dying");
      break;
   }
}

I could also add invisible "Obj" in specific places for when a player walks over a certain place. I don't know if this is a good idea but I can't think of other means to do it. How is it commonly done? Also how do I keep track of events that already happened?


texts: Load a simple text file through asset manager in libgdx

texts:
It's easy to load a simple text file from the internal:

Gdx.files.internal("data/colors.txt");

But I currently use an AssetManager to load assets that are defined in an array of AssetDescriptor<?>s while a loading screen (with a progress indicator) is shown. So I'd like to use something like this in my array of descriptors:

...
new AssetDescriptor<_type_>(Gdx.files.internal("data/colors.txt"), _type_.class),
...

I'd like to load the file through an asset manager, so the overall progress can be displayed as the data/colors.txt file can get very large and therefore take longer to load (I use an tool to automatically generate a very long list of color definitions: RRR,GGG,BBB,AAA, each in the range of 0-255).

Is there a good way of doing this?


texts: Why is RK4 better than Euler integration?

texts:
At the end of these great slides, the author compares all the different integrators presented. One way or another, they all fall short except for Improved Euler Integration and Runge Kutta 4 Integration, which both pass all tests.

I suppose I should mention that I am working on a 2D game that isn't very physics intensive. I'm just curious as to where Improved Euler Integration would fall short and RK4 would have to be used instead.

My game consists mostly of simple gravity (jumping and falling), movement along the X and Y axes, and bounding box collision. Is it worthwhile to implement RK4 or would Improved Euler be sufficient? I see many discussions where Euler Integration's users are chastised, but from what I can see, Improved Euler is quivalent in simple 2D matters. I imagine it'd also be faster.


texts:
I want to calculate the distance between the list of game objects So element will check its distance with every other element and so on, I am doing this with following code it works but not efficient enough. Can anyone tell me the correct way to use loops in the job system?

enter struct Field: IJobParallelForTransform
{
    public NativeArray<float> Dist;
    public Vector3 PlayerPos;

    public void Execute(int i, TransformAccess transform)
    {

          Dist[i] = Vector3.Distance(PlayerPos, transform.position);

    }
}

public List<Transform> Childrens;//All gameobjects list

public TransformAccessArray ALlObjects;

NativeArray<float> distances;

void Start ()

{

    ALlObjects = new TransformAccessArray(0, -1);

    distances = new NativeArray<float>(Childrens.Count, Allocator.Persistent);

}

   void Update()

{

    for (int i = 0; i < Childrens.Count; i++)

    {

        Field job1 = new Field()

        {

            Dist = distances,

            PlayerPos= Childrens[i].position,

        };

        JobHandle jH = job1.Schedule(ALlObjects);

        jH.Complete();

        for (int j = 0; j < distances.Length; j++)

        {

            if (distances[j] <= 0.8f && distances[j] > 0)

            {

                break;

            }

            if (distances[j] > 0.8f )

            {

            }

        }

    }

}


texts:
My UI designer has made a lovely photoshop PSD of the UI and everything pretty. The biggest problem I'm having is converting some of the more elegant fonts used into something renderable in-game. Is there a way to convert these font styles in Photoshop to a bitmap font of some sort?

I need to be able to render text like this inside my code:


texts:
I want to ask you about some resources to learn simulating soft bodies, do you know some good knowledge sources?

I asking because I want to make car crash simulator, I've made something but it didn't work well. :/


texts:
I have to rotate few objects on an ellepsoidal(Capsule shaped) track and at the run time speeds are assigned to the objects from the server as this is a betting game which I am developing in Unity 5 using C#.

So can I use Bezier Curves for that if yes then how do I use that?


texts: Sometimes can't use the rendered mesh as a collider in Unity?

texts:
Most of the times I can use the Mesh Filter's mesh as collider in Mesh Collider

But sometimes there is just nothing. No collider. Why?

I used this free asset: https://assetstore.unity.com/packages/3d/environments/fantasy/green-forest-22762


texts: Unity procedural skybox shader texture stretching

texts:
I am using the procedural skybox shader that Unity provides, but have tweaked it so that I can have a cloud texture.

The problem I have, is that the texture is not tiling correctly, even though it is a repeatable pattern.

In the GIF below you will see the stretching, but it tiles everywhere else.

Here is the test cloud texture I am using.

Am not doing anything unusual in the shader I don't think.

// In the vertex (copied this from another shader, could this be the problem?)
OUT.uv = TRANSFORM_TEX(v.uv, _Sky_Clouds);

// in the fragment before returning the color

c = c + tex2D(_Sky_Clouds, IN.uv);

How can I use the cloud texture so it tiles around the whole skybox without stretching?

The look I am trying to achieve is like this...

That image is from this video tutorial by BlenderGuru.

https://www.youtube.com/watch?v=9Q8PwcDzb8Y&t=1046s


texts: Why place entity config outside of scripts?

texts:
I've seen a lot of games that define the entity components in script files, but when they configure each entity and specify what components it has, they use some other file format (like XML). Why do they do that?

I'm asking mostly to see what others' rationale was for this. I also configure my entities outside of scripts (though I chose JSON not XML). My reasons for doing this are to make it easier for me to implement save games and also because I think this kind of configuration is better organized in something like XML or JSON.

@Christopher Larsen's answer: Too long to post as a comment

I fear you might have deviated a bit from the subject of the question. The problems you are describing are more related to hierarchy-based entities; note in my question I mentioned I was talking about component-based entities.

Here's an example of what I wanted to ask. Below are two alternative ways to configure an entity: through the script and through an external JSON file. My question was, why do so many people prefer to configure the entity outside of scripts?

A base Entity class:

class Entity:
    def __init__(self, name):
        pass
    def addComponent(self, comp):
        pass

The script approach:

orc = Entity('Orc')
orc.addComponent(PositionComponent(3.4, 7.9))

The JSON approach:

{
    "name" : "Orc",
    "components":
    {
        "PositionComponent": {
            "x" : 3.4,
            "y" : 7.9
        }
    }
}

I already stated my reasons for using this approach, which are technical and organizational. I wanted to know why so many others (from what I've seen) use this.


texts:
I'm currently wondering how to properly structure game code.

I have come across MVC (Model View Controller) method/approach, which seams to be a decent way to get a good extendable structure.

However, I'm wondering how one should put in animations and visual transitions into this model?

The simples example I can think of is Tetris.

In many newer Tetris clones, if a line is cleared, before it's removed from the screen, it sometimes flashes in different colors for visual effect. Where does this fit in the model?

The way I understand is that MVC has a controller that should update the board state, and if one line is full, it should be removed, yet the model would do this in a single frame? The view should not interact with the model, so what would be a good way to make these visual effects appear without loosing the benefits of decoupled logic and rendering?

Sorry if this is an ill posed question.

Thanks in advance : )


texts: Do I need path finding to make AI avoid obstacles?

texts:
How do you know when a path-finding algorithm is really needed?

There are contexts, where you just want to improve AI navigation to avoid an object, like a space -ship that won't crash on a planet or a car that already knows where to steer, but needs small corrections to avoid a road bump.

As I've seen on similar posts, the obvious solution is to implement some path-finding algorithm, most likely like A*, and let your AI-controlled object to navigate through the path.

Now, I have the necessary skills to implement a path-finding algorithm, and I'm not being lazy here, but I'm still a bit skeptical on if this is really needed. I have the impression that path-finding is appropriate to navigate through a maze, or picking a path when there are many alternatives. But in obstacle avoidance, when you do know the path, but need to make slight corrections, is path finding really necessary? Even when the obstacles are too sparse or small ?

I mean, in real life, when you're driving and notice a bump on the road, you will just have to pick between steering a bit on the left (and have the bump on your right side) or the other way around. You will not consider stopping, or going backwards. A path finding would be appropriate when you need to pick a route through the city, right ?

So, are there any other methods to help AI navigation, except path-finding? And if there are, how do you know when path-fining is the appropriate algorithm ?

Thanks for any thoughts


texts: How do I mask graphics in Unity to create a searchlight effect?

texts:
I'm trying to make a searchlight-style punchout mask effect in Unity 2D. This is the effect I'm looking for:

That animation is made in Fireworks, using a white to black gradient circle masked on top of the map image below it. Here's a single frame for closer viewing.

How can I create this effect in Unity?

So far, I have a separate camera that only renders the white circle using a culling mask, but I'm not sure what to do from there.


texts: LibGDX - ImageButton and textures for touchDown and touchUp

texts:
I have problem with setting my ImageButton. I want to have two different textures in my button, first when button is touchDown, and second when my button is touchUp. But I all time have touchUp texture. Here is my code:

buttonUp_texture = assets.manager.get(assets.buttonUp);
Drawable buttonUp_drawable = new TextureRegionDrawable((new TextureRegion(buttonUp_texture)));

buttonDown_texture = assets.manager.get(assets.buttonDown);
Drawable buttonDown_drawable = new TextureRegionDrawable((new TextureRegion(buttonDown_texture)));

tapBtn = new ImageButton(buttonUp_drawable, buttonDown_drawable);

and listener:

    startButtonListener= new ClickListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            Gdx.app.log("Button", "TouchDown");
            game.setScreen(gameScreen);
            return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            Gdx.app.log("Button", "TouchUp");
            super.touchUp(event, x, y, pointer, button);
        }
    };

Listeners work correctly so I dont know what is wrong.


texts: Collision detection between axis-aligned bounding box and bitmap (pixel perfect) terrain

texts:
Working on a Worms-type game, I have my objects in bounding boxes and they sit on the pixel terrain.

Currently I am able to successfully do the collision detection for objects when they enter the game by checking the middle-bottom pixel of the bounding box, if it is solid, reduce the x and y velocity to 0, other wise keep moving down at a value of gravity.

The trouble comes in when I start to move the "player sprites" as they can walk into walls and I'm not sure how to approach how to detect collision if moving into pixels, and finally how to resolve these collisions.

I need to be able to detect solid walls I cannot pass, and gradient hills where the player should "walk up".

Could you help point me in a way to do this or how it has been done in the past?


texts: Unity Android Immersive mode leaving a black bar in the soft key area?

texts:
The black bar is not hiding anything. Everything is drawn above it. But the black bar is there in place of the soft keys even when they are hidden.
I don't know how to hide it and render using whole screen.
The bar is only visible with device having soft keys not for device with physical keys.
 I have set the Screen.fullScreen = true.

Unity 2018.3.4f1


texts: How to change the time dilation using C++ in Unreal Engine?

texts:
I searched a bit and found a blueprint solution which does this but I've just started using Unreal and I prefer C++ instead of this visual programming thingy.

I'm looking for a Unity-like Time.timeScale property which could be easily set during runtime.

Is there a thing like that in Unreal?
I just want to play with changing the speed of time of the whole world.


texts: What's a good Flash game development tutorial, in FlashDevelop, for an absolute beginner?

texts:
Ok, here's my situation: I'm tutoring a 14yo homeschooled student with very little previous programming experience, and I'd like to teach her how to program.  I think that Flash Actionscript 3 is a good resource for her to start out with, mostly because she seems to have an interest in game development.

I've decided that FlashDevelop, used alone, is the best interface for her to use, especially as she becomes more proficient in Flash.  The trouble is, while I am an extremely competent Web programmer in other languages, I have no experience with Actionscript at all, and I can't find a good tutorial for her to use.

The tutorial doesn't need to have the algorithmical basics of programming, like the concept of loops, if statements, OOP, etc; I can teach her those.  What I need is a tutorial that teaches Actionscript SYNTAX and walks you through the steps of game development in FlashDevelop.  Once I have that, I can do everything else.

Can anyone help me?


texts: Are there good free ebooks on game development? I don't care if they are theoretical or technology specific, I want to start reading one free book that worth it.


texts: Creating an animation for materials in code (Unity)

texts:
I have a function where you click on an object and it changes the color and emission of a specific material, every object has multiple materials with different order.

var emissionColor = mat.GetColor("_EmissionColor");
List<Material> materials.AddRange(t.GetComponent<MeshRenderer>().materials);

 foreach (var m in materials)
    {
        if (m.name.Equals(matName))
        {
            //Debug.Log(m.name);
            m.EnableKeyword("_EMISSION");
            m.color = mat.color;
            m.SetColor("_EmissionColor", emissionColor);

        }
    }

So far I'm changing the color once but I would like to have it transition into a different color every 10 seconds, I tried using the animator but it keeps changing the wrong material. Is there a way to do this animation in code?


texts: OpenGL Planet Generation - Simple Matrix Issue (Planet “Spins” With Mouse)

texts:
I originally asked this question on StackOverflow & was directed here by a commenter.

Im currently working on a OpenGL planet rendering. I'm using the Tessellation pipeline. So far things are going very well bar one issue. It's at the stage where I've been banging my head off it for ages and feel like progress isnt happening.

First of all here is a gif of what I'm dealing with. Essentially my problem is that whenever the mouse is moved the planet rotates as if its "looking" at where the camera is pointing.

There are some graphical issues but they are due to me simply repeating the same heightmap across the whole cubemap. Since it doesnt match up on the sides there are clear seams.

Below is my evaluation shader:

void main(void) {
    vec4 p0 = gl_in[0].gl_Position;
    vec4 p1 = gl_in[1].gl_Position;
    vec4 p2 = gl_in[2].gl_Position;
    vec3 p = gl_TessCoord.xyz;

    Normal_FS_in = mat3(transpose(inverse((MV)))) * (p0*p.x + (p1*p.y) + p2*p.z).xyz;

    float displacment = texture(tex1, Normal_FS_in).r * 800;
    gl_Position = MVP*(p0*p.x + (p1*p.y) + p2*p.z) + (vec4(vec3(displacment,displacment,0) * normalize(Normal_FS_in),1));
}

Its pretty simple. The shader calculates a normal for the output vertex. This is then used to grab a displacement value from the heightmap which is a cube map. Then GL_Position is calculated. What I've been trying to work out is if my problem lies in the shaders or in the rest of the package.

My attempts have largely been tinkering. I've moved all normal related stuff into the evaluation shader rather then calculating it in the vertex shader and passing them through to the control and evaluation shaders.

The issue only occurs when the mouse is moved.

Any suggestions would be fantastic - hopefully all I'll need is a pointed in the right direction.

Edit - Doing the inverse transpose of the modelview matrix OR view matrix yields the result in the gif. Using the model matrix leads to distortion of the normals when the camera is moved, such that the terrain bends about the place.


texts: Emit particles from only some parts of a mesh

texts:
I have a 3D mesh with 3 sub meshes in it, for 3 different materials.

I would like particles to spawn from the mesh, but only from location where one of the material is assigned.

How can I make this happen?


texts: Writing the correct value in the depth buffer when using ray-casting

texts:
I am doing a ray-casting in a 3d texture until I hit a correct value. I am doing the ray-casting in a cube and the cube corners are already in world coordinates so I don't have to multiply the vertices with the modelviewmatrix to get the correct position.

Vertex shader

world_coordinate_ = gl_Vertex;

Fragment shader

vec3 direction = (world_coordinate_.xyz - cameraPosition_);
direction = normalize(direction);

for (float k = 0.0; k < steps; k += 1.0) {
....
pos += direction*delta_step;
float thisLum = texture3D(texture3_, pos).r;
if(thisLum > surface_)
...
}

Everything works as expected, what I now want is to sample the correct value to the depth buffer. The value that is now written to the depth buffer is the cube coordinate. But I want the value of pos in the 3d texture to be written.

So lets say the cube is placed 10 away from origin in -z and the size is 10*10*10. My solution that does not work correctly is this:

pos *= 10;
pos.z += 10;
pos.z *= -1;

vec4 depth_vec = gl_ProjectionMatrix * vec4(pos.xyz, 1.0);
float depth = ((depth_vec.z / depth_vec.w) + 1.0) * 0.5;
gl_FragDepth = depth;


texts: What is the best way to import autocad models into unity?

texts:
I just got someone to create a 3d environment for my game in autocad 2015. I exported that environment and imported it into unity but that doesn't work well as I am unable to see my environment in the scene view correctly.

Any suggestions on how to do it better? I am not good with 3d modeling and I ever used autocad models in unity before. Any kind of help is highly appreciated. :)


texts: How to continue firing when button is touched?

texts:
How to continuos firing when user touch (and keep press) a button in Android/iOs?

Using onClick, i can fire only one shot.

Is there an event like "keep-touch" ?

Thanks


texts: Cocos2D V3 Blur effect performance test without iOS device

texts:
I am testing the blur effect (CCEffectBlur) in Cocos 2D V3 and I found that when I add an effect to an EffectNode it takes up to 5 seconds to appear in the IOS Simulator screen. (I know that the IOS Simulator is not to test performance)

When I run the same code in my device (iPhone 6), it appears almost instant.

My problem is to test the performance in old devices like iPhone 4S or iPhone 5 but, unfortunately, I don't have those devices to do some tests.

Is there any way to check my game's performance on those devices without the devices?

This is what I am testing.

I have a hierarchy with an EffectNode as a root node.
I am using a code like the following to add the effect
effectNode.effect = [CCEffectBlur effectWithBlurRadius:10];


texts:
I have a Line Renderer component with 4 points, I would like to disable and enable the last 2 points at a certain time. My question is, how would I in code (C#) enable and disable individual Line Renderer points?

Thanks in advance!


texts: 8 directional movement - Maintain vertical position

texts:
I have a top-down game that has 8 directions of movement (top/down/left/right/topright/topleft/bottomright/bottomleft).  There are sprites for each direction of movement.  This is just an example spritesheet:

The problem is when I want to retain the vertical position.  When I let go of the buttons on the keyboard, it polls the keys quickly and ends up facing the character in either left/right/up/down position depending on the last key that was released.

I added a delay for polling the keypresses, but I do not like this solution as it creates a noticeable lag.

Can anyone think of logic that would be able to allow my sprite to retain the proper direction when the keys are unpressed?  Here is the current code:

if (kbState.IsKeyDown(Keys.Up) && kbState.IsKeyDown(Keys.Left))
    character.ChangeDirection(Direction.UpLeft);
else if (kbState.IsKeyDown(Keys.Up) && kbState.IsKeyDown(Keys.Right))
    character.ChangeDirection(Direction.UpRight);
else if (kbState.IsKeyDown(Keys.Down) && kbState.IsKeyDown(Keys.Left))
    character.ChangeDirection(Direction.DownLeft);
else if (kbState.IsKeyDown(Keys.Down) && kbState.IsKeyDown(Keys.Right))
    character.ChangeDirection(Direction.DownRight);
else  if (kbState.IsKeyDown(Keys.Up))
    character.ChangeDirection(Direction.Up);
else if (kbState.IsKeyDown(Keys.Down))
    character.ChangeDirection(Direction.Down);
else if (kbState.IsKeyDown(Keys.Left))
    character.ChangeDirection(Direction.Left);
else if (kbState.IsKeyDown(Keys.Right))
    character.ChangeDirection(Direction.Right);

Edit

Settled for the following code:

float delay = 0.04f;
float DELAY = 0.04f;
....

//Get movement
delay -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (delay < 0)
{
      int vertical = kbState.IsKeyDown(Keys.Up) ? -1 : kbState.IsKeyDown(Keys.Down) ? 1 : 0;
      int horizontal = kbState.IsKeyDown(Keys.Left) ? -1 : kbState.IsKeyDown(Keys.Right) ? 1 : 0;
      movement = new Vector2(horizontal, vertical);
      delay = DELAY;
}

character.Update(gameTime, movement);

Seems I have to use a delay in order to get this to work.  Thanks for the feedback guys.


texts:
I want to make an iPhone game and I was wondering if somebody could point me to some resources. Before you rage and close this, I am not looking for just a tutorial on programming, I could just google that.

I need to find a tutorial on how to actually make a game, as in how to organize your code, what type of methods to run in separate threads, how to manage these threads in a game, etc. I already know everything I need; I can write a physics engine from scratch, I can write a 3D graphics pipeline from scratch, and so on. What I cannot figure out is how to combine all of this knowledge into correctly and efficiently making a game. Obviously for this one would probably go to college, but seeing as I am still in high school, that is not an option.

If anyone would know some tutorials or resources, any pointers would be appreciated.


texts: Modeling the logical structure of a game

texts:
I have been working on a game for a while and have encountered a problem stated below. I have been reading Sandi Metz's book on OOP (the Ruby one) and it made me wonder whether there is a way to visually represent all the classes of a program.

The problem: the code of the game is slowly but surely becoming harder to maintain, or should I say, to... fathom. To comprehend.

I need to know if there is a way to visually model the logical structure of the game's classes, and maybe some standalone pieces of code, and how classes interact with each other, OR a way to represent game entities from a game design point of view because it will be immeasurably easier to work on the game from both a technical and an artistic point of view if I had a visual model of the game's structure.

I do not need UML diagrams or a simple flowchart because they have too much info: knowing the fields and methods of my classes or the logical algorithm of my code is not what I need.

I have thought about using ARIS or BPMN for it, but I am not entirely sure whether the strict rules of these BPM notations would fit well with the dynamic and ever-changing nature of a game.

I apologize if this stack exchange is not the right place for this question. If no complete solution exists, then I am willing to create my own, perhaps with Qt.

Update: I have read the aforementioned book further and found out about sequence diagrams. They would fit very well, but I'm still interested whether a tool was created specifically for making games.


texts:
I need some help with the SpriteFont. I want a different font for my game, other than Kootenay. So, I edit the SpriteFont xml, i.e:

<FontName>Kootenay</FontName>

or

<FontName>Arial</FontName>

No problem with Windows fonts, or other XNA redistributable fonts pack. However, I want to use other fonts, that I downloaded and installed already, they are TTF or OTF, both supported by XNA.
My problem is, I cant use them, I got this error:

  The font family "all the fonts i tried" could not be found. Please ensure the requested font is installed, and is a TrueType or OpenType font.

So, checking at the windows fonts folder, I check the properties and details of the fonts, I try all the names they have, and but never works. Maybe I need some kind of importing or installing in order to use them, I dont know, and I hope you guys can help me, thanks!


texts:
I am currently doing measurements on a test scene implemented in OpenGL 4.5 with different "setups".

I noticed that in case I have a very high amount of FPS (1550 in this specific case), SwapBuffer does stall about every 20th frame and the frame time increases from ~0.5ms to ~1.2ms.
This does ONLY happen when the FPS is above a certain threshold.
I already figured out that it is not related to pre-rendered frames (i disabled pre-rendered frames in the NV control panel) and it is also not related to vsync (wglSwapIntervalEXT(0) is used).

Can someone tell me what might be causing this stalls/lags or wathever.

I attached two screenshots made with Nsight.

The first shows a "healthy" setup with no stalls:

While the seconds shows the setup with the stalls:


texts:
I'm writing a C# game in Mono, and I want the game to be as modular as possible.
I've started by writing the whole Item (inventory) System of the game in a seperate .dll library
But I've hit a problem. I want Items to have effects, so I've written a base Interface for this:

interface IBehavior
{
    bool ApplyBehavior(Player destinationPlayer);
}

I'm following guidelines from the answer on this post regarding the (Unit, Effect, Behavior, Ability [Lets call it UEBA]) structure. Problem is that Player is a class from like the main module in the game so I assume this breaks modularity in the code.
What would be the best solution to fix this conflict?
I'm considering writing another, separate module, of UBEA, that will use Player and then the Item System module will use that module instead of the main module, and then the UBEA module will break modularity.
Should I also move Player to another module?
Am I even able to create full modularity if this is the model of things I want to create?

Thanks for the answers!


texts: How can I see the height of an object within Blender?

texts: I'm fairly new to Blender. I know there is the "Transform" section in the Object menu of the Properties tab, which contains Location/Rotation/Scale of a selected object. What I'd like to know is if there is way to tell the height (Z) of an object, or just the selected face?


texts: Create a series of points round a globe (Polar to Cartesian) C++

texts:
I am trying to create a series of waypoints for my globe planet, in a little simulation I'm doing, and I'm trying to use polar to cartesian coordinates, I learnt this formula off its wikipedia page. Though I still don't quite understand it.

https://en.wikipedia.org/wiki/Spherical_coordinate_system
Attempt 1; This is the image of my first attempt, I do not want to cluster the points near the poles, the poles are also at the completely wrong point, I will supply my code later on. But also I do not want to put points too close to the poles, as they are not in use, and due to camera gimbal locking, there is no point me going too far close to the north or south pole in my program.

Attempt 2: Now I know how to create a single line, and the code I use for this is provided below. I sort of figured this out by just testing out different values and seeing how it came about.

Now what I want to do to this, I think as the way I wish to construct it, is to get the vector of each of those points, and rotate them round the centre of the planet which in this example is (0,0,0)

I want to create a single line of longitude per pas, so I can number the points 0-50 on each line, that will allow me to use it as a connected grid,lets say 0-50 going upwards, so that if i start at point 1 which would be the first point near the south pole, and I want to go to the next row I would add 50 to get to 51 (which would be the point right of it) or take 50 to get the point left of it), and so on and so forth, this will allow me to easily join waypoints for pathfinding setup.

I made another attempt in the link [ABOVE], where I try and make a nested for loop and change the latitude per step, but it does not get the desired result, I have even swapped the values of lat and longitude around in the code and the coordinates are the same.

Latitude = should be the angle from east to west.
Longitude = should be the angle north to south.

To do this I think but I am not sure, I assume I will have to store a temporary value of each of those points, and then create a new vector from them, by rotating their vectors around the origin of the planet (0,0,0) and then creating a new set of these points at the temporary vectors.

Does anybody have an idea how to help me solve my problem, as Image 4 is the best explanation I can think of showing my problem to explain what I am trying to achieve.


texts: How to use This Keyword and using iterators to call class methods?

texts:
I've been over this for a long time, I can't seem to understand what is wrong, is the use of the this keyword right? I want to add the instance of the class that is being created to the vector 'allEntities' in the constructor, or am I not using the iterators right? I'm very new to c++ and programming in general so all help is appreciated.

GameObject.h

class GameObject {

public:
    GameObject(const char* texturesheet, SDL_Renderer* ren, int x, int y, int _maxHp, int _currentHp, int _strength);
    ~GameObject();

    static std::vector<GameObject> allEntities;

    void update();
    void Render();
    void movement(const char* coord, bool positive);
    int getMaxHp();
    void addMaxHp(int change);
    int getCurrentHp();
    void setCurrentHp(int change);
    int getStrength();
    void changeStrength(int change);
    void attack(GameObject &other);
    int getX() { return x; };
    int getY() { return y; };
    void setDirectionFacing(char direction) { directionFacing = direction; };
    char getDirectionFacing() { return directionFacing; };
private:

    int x;
    int y;
    int strength;
    int maxHp;
    int currentHp;
    char directionFacing;

    SDL_Texture* objectTexture;
    SDL_Rect srcRect, destRect;
    SDL_Renderer* renderer;

};

GameObject.cpp

GameObject::GameObject(const char* texturesheet, SDL_Renderer* ren, int xx, int yy, int _maxHp, int _currentHp, int _strength)
{
    allEntities.push_back(*this);
    renderer = ren;
    objectTexture = textureCreator::loadTexture(texturesheet, ren);
    GameObject::maxHp = _maxHp;
    GameObject::currentHp = _currentHp;
    changeStrength(_strength);
    x = xx;
    y = yy;
}
GameObject::~GameObject()
{

}

void GameObject::update()
{

    srcRect.h = 48;
    srcRect.w = 48;
    srcRect.x = 0;
    srcRect.y = 0;

    destRect.x = x;
    destRect.y = y;
    destRect.w = srcRect.w * 1.5;
    destRect.h = srcRect.h * 1.5;
}

void GameObject::movement(const char* coord, bool positive)
{

    if (coord == "x" && positive == true)
    {
        y -= 4;
        setDirectionFacing('w');
        std::cout << 'w' << std::endl;
    };
    if (coord == "x" && positive == false)
    {
        y += 4;
        setDirectionFacing('s');
        std::cout << 's' << std::endl;
    };
    if (coord == "y" && positive == true)
    {
        x += 4;
        setDirectionFacing('d');
        std::cout << 'd' << std::endl;
    };
    if (coord == "y" && positive == false)
    {
        x -= 4;
        setDirectionFacing('a');
        std::cout << 'a' << std::endl;

    };

}

void GameObject::Render()
{
    SDL_RenderCopy(renderer, objectTexture, &srcRect, &destRect);
}

int GameObject::getCurrentHp() { return currentHp; };

int GameObject::getMaxHp() { return maxHp; };

void GameObject::setCurrentHp(int change) { currentHp += change; };

void GameObject::addMaxHp(int change) { maxHp += change; };

int GameObject::getStrength() { return strength; }

void GameObject::changeStrength(int change) { strength += change; }

void GameObject::attack(GameObject &other)
{

}

game.cpp

GameObject* player;
player = new GameObject("player.png", renderer, 10 , 10, 10,  10, 2);
    for (std::vector<GameObject>::iterator it = GameObject::allEntities.begin(); it != GameObject::allEntities.end(); it++) {
        int hp = it->getCurrentHp();
        std::cout << hp << std::endl;
    }

I expect to print out the hp value which is 10, but instead it prints 0 instead.

Also I need this vector so when the player attacks, it checks every entity and sees if it is in the area of the attack in a for loop, is there any better way to do this?


texts:
So being a primarily c/c++ developer, I've always thought that the only option for mobile game development for me was using iOS, which allows for c/c++ (and minimising objective C).

I heard from a friend though, that android has a native development toolkit which allows for c++ code to work on android.

Has anyone used this, and if so, how do you find it? I mean, will it "just work" like iOS, or are there more considerations that need to be taken care of due to the wide variety of android devices available?


texts: Scrolling 2D sprites on a map with a camera

texts:
I'm working on a 2D sprite-based strategy-type game (ok, full disclosure: it's a tower defense game), and I'm having a problem getting the actors to behave correctly when I move the camera.

I've got a Camera class, which contains data and methods for moving the camera and exposing its' current position. When I draw the background, I offset the background thusly (and it works great):

var backPos = new Vector2(background_bounds.X - camera.CameraPositionX,
                          background_bounds.Y - camera.CameraPositionY);
spriteBatch.Draw(background_texture, backPos, Color.White);

My sprites each have a GraphicsComponent that directs the rendering. I've been playing around with different combinations, but none seems to give the proper (expected behavior); I lose collision detection (done via my CollisionComponent object), or the physics misbehave, etc, because actor's position is different than what the other components expected. Here's the GraphicsComponent.Draw(...Camera camera):

 //...snip
 var adjustedPosition = new Vector2(actor.Position.X - drawOffsetX,
                                    actor.Position.Y - drawOffsetY);
 //Uncommenting this line doesn't work either - just makes things seem worse
 //actor.Position = adjustedPosition;
 DrawContext.Draw(actor.Texture, adjustedPosition,
                  actor.SpriteBounds, DrawColor);

How do you folks approach applying camera offsets to sprites in a way that avoids exposing the camera to every component? Do you offset the actual position by the camera's position, or do you simply render the position with the offset, and compensate elsewhere?


texts: Drawing a hexgrid on a canvas, yet making it zoom/scrollable?

texts:
I'm developing a game in JS / PHP. The game is basically a 2D plane (hexgrid) where each hex represents a location in space.

In total, I'm drawing 25 * 25 hexes on a 1000x1000 canvas. I also draw indicators in those hexes. Both the hexgrid as well as the indicators can be redrawn using a zoom variable that is altered by using the mousewheel and then redrawing all content * zoom.

This works ok up to a certain point. If you scroll in too "deep", the hexes become too big and the canvas, from its base size, cant display 25*25 hex anymore.

So now I require a "scroll" function where one for example would hold the mouse button and move it left or right to "shift" the view. Unfortunally I have no clue how to realize this, especially because I would require a "focus" variable to indicate at which position the canvas' center (width, height/2) is currently located at in context to the hexgrid.

Long story short, using a canvas element to display an object array, how would I go about adding a scroll function which redraws my canvas in context to the relative position?

For reference, my hexgrid is an object that holds an array of 625 subobjects (the hexes), which each have a row/column variable as well ALL 6 hexagon points in pixel-coordinates.


texts:
I'm new to c# and coding, sorry if I sound like a noob... I don't know how to fix the waitforseconds error, and I don't know what's wrong.

public float restartDelay = 2f;

public TextMesh failText;
public TextMesh failTextGame;

private void Start()
{
    failTextGame.text = "";
}

System.Collections.Generic.IEnumerable<bool> OnTriggerEnter(Collider other)

{
    if (other.gameObject.CompareTag("Wall"))

    {

        failText.text = "Game Over!";
        failTextGame.text = "Try Again";
        yield return new WaitForSeconds(restartDelay);
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

}


texts: How can I make a C++ countdown timer that doesn't freeze user input?

texts:
I'm planning to use the Sleep() function to implement a countdown timer. But this freezes the input of the user at the same time. Thus I wanted to ask if it is possible to have the countdown still running in realtime, whether they're typing or not; or in other words not freeze everything.

Is it possible? If so, how?

Example : Pop Quiz with Timer


texts: How to attach an UI button to a prefab and follow it in Unity2D

texts:
My plan is creating a button above my prefab (a tree) and whenever my character is detected, the button will appear and allow me to click on it to active a dialog. I just want my trees are randomly spawned and stay still so it's not "follow" actually but I would like to know in that case too.

I did some researches but most of them were about Text and HP/MP things, which weren't used by UI system.

One more thing, I kinda new to code so it would be fantastic if I got a full code (Button follow only).

Thanks in advanced.


texts: How well (or badly) does Minecraft SMP scale?

texts:
Has anyone tested and collected some data about how well does Minecraft SMP scale, with an increasing number of players (up to large amounts of players)?

I.e. the bottlenecks are:

mostly in the server or in the client or both
if the players are all in the same area, or if they are in different areas, or it is irrelevant where they are


texts: When should one use LibGDX's FrameBuffer and when SpriteCache?

texts:
In my game I have some graphics that I want to draw once and only redraw whenever something is changed by the player. Now, I'm wondering, whether I should use the FrameBuffer or the SpriteCache class.
I know that a framebuffer is much more general concept and also works for 3D, while a SpriteCache is only for 2D. However it seems to me that they would both make sense in my use case, so I'm wondering..

What are the differences, drawbacks and advantages of using one over the other?


texts: Character doesnt move along with his rotation

texts:
Decided to change my character movement from transform.Translate to a rigidbody movement, the only problem is that my character is not moving to where he is facing, also it falls really slowly in the Y axis. Heres the code related to the movement:

    float moveHorizontal = Input.GetAxis("Horizontal") * rotSpeed;
    float moveVertical = Input.GetAxis("Vertical") * speed;

    rb.velocity = new Vector3(0, 0, moveVertical);
    transform.Rotate(0,moveHorizontal, 0);


texts: Unity 5.6 - Can no longer select empty GameObject with Gizmo in editor

texts:
Has anyone else noticed this?
I'm using the latest version of Unity (5.6.0p2) and it appears Gizmos are no longer selectable by default.

Is there any way to restore this behaviour?

Some of my objects are essentially empty (no meshrenderer/Filter) with a MonoBehavior attached, which require a gizmo drawn sphere so it can be selected.

Is there a better/more appropriate way of making non-mesh gameobjects selectable in the editor that I'm not aware of?

I understand I could use Handles to detect a mouse click but this doesn't allow for simple drag selection (marquee tool) if I want to select a load at once.


texts: I heard that there was a faster method of displaying vertices, rather than recreating the GL_TRIANGLES, each time the scene is drawn. I thought I read somewhere that this method was  obselete. Why would the OpenGL group remove something that was faster? Even if it is obselete, how would I go about implementing this?


texts: Is it feasible to stream your game when the screen is small?

texts:
My game consists of a very small screen (256x256). Behind that screen, though, there is a lot of very, very expensive ray tracing going on, which requires a very powerful GPU. Moreover, all clients see a variation of the same scene, so, a single GPU could render the whole scene for everyone.

Given that scenario, I had the idea of just rendering the screen on the server and streaming it to the clients. This way, one could run my game even on very weak machines. But I guess the bandwidth use could make it unpractical; is it possible to stream a 256x256 screen at 30 fps without delay and in a lossless format?


texts: How to properly handle equipment enchants

texts:
In my game, the player starts with a set of equipment and unlike many other hack-and-slash RPG's, this base set of stuff never changes - the player never acquires a new weapon or armor.

The only way how to keep up with ever stronger monsters is to enchant the equipment with spells. Each piece can hold a couple of different enchants and as the player slays monsters he gets access to stronger spells for enchanting.

The problem is some encounters favor different enchant strategies than others. While for one type of monster it would be better to go for resistance against magic, another monster is not using magic at all so physical resistance is more important. I want the players be able to replace their enchantments obviously, but i don't want the player to feel like he must redo all his gear before every encounter to be prepared - that would be too annoying.

How would i go about limiting the availability of removing enchants from gear so it does not become a tedious thing to do, but instead is an exciting event in gameplay? (like: "Cool i can now upgrade those old enchants on my staff which will make slaying those ogres easier!") Also the possibility of removing enchants shouldn't be too rare, since it's the core gear-progression mechanic.

The only thing i could think off was using special scrolls to remove the enchants. These scrolls would drop from monsters and the drop chance will be based on how "weak" the enchants the player uses are compared to his level. The weaker the enchants, the higher a chance to get a disenchant scroll and vice versa. However there is a problem that the player can simply farm for the scrolls and save them for later thus allowing him to redo his gear before every encounter in end-game, where the monsters are the hardest. I would like to avoid that.


texts:
Last weekend, I spent several hours writing a basic entity component model, in JavaScript. I was largely referencing the Ash Actionscript game engine. I successfully worked out how the systems, components, nodes, and entities all link up, but one thing that eludes me is how to implement the "watcher" that checks the entities for their components, creates nodes for them, adds those nodes to the various systems automatically, and watches for any changes in the components on an entity. I was a bit confused by the way it works, in Ash, and all of the posts and tutorials on the subject that I have read seem to forgo the details of that part of the implementation.

Right now, I currently have the following:

Entity, which is assigned components.
Engine, which keeps a track of the systems and entities.
Node, which contains references to the components in an entity that we want the system to modify (I am currently creating these, manually, and adding it to the system).
Component, which contains the data to be modified by the system.
System, which operates on the nodes, which in turn change the data in the entity.
I also have various other classes, dedicated to holding lists of the various objects.

How do I go about creating the "Watcher" component?


texts: How do I implement 2d color animation like in this video?

texts:
link on youtube
at 1:38 - 1:42, purple things (I think this is particle system) that come off from the moon.

Someone else had decompiled the game in the past, and the assets shows that the dark blue area around the moon (after purple things come off) is just background image. So my assumption is that there are many of those 'purple things', that use additive blending to give different density of 'purpleness'.

The details that I'm looking at are:

As those purple things come off completely from the moon, it forms
jagged shapes
At the edge of those jagged shapes, color blends
smoothly instead of sharp turn between purple and dark blue(I know
how to do it with simple shapes, but in here, the jagged shape
itself constantly changes)
further from edge between dark blue and
purple, at the light purple direction, the density of purple is nice
and smooth

I'm pretty familiar on animating objects by manipulating transform,  but this one seems like a lot of color works with programatically created shapes, any idea?


texts: Does duplication happen quicker than generation?

texts:
I am evaluating performance of bullet instantiation methods in Unity. I have a thing against prefabs. So each bullet is made from a function that sets the shape material, scripts and behaviors (tracking, velocity, duration, etcetera). Call this the "ammo type" if you like. Here are my instantiation methods:

Generate one bullet from script.  Disable it. Instantiate(duplicate) new bullets from this bullet and enable them when gun fires.
Each time the gun fires, generate a new bullet from the script. Still technically a duplicate but arrived at through a different method.

Which of these would have better performance? Would it be a drastic difference or a minor one?

The first method makes much more sense than the second. However there is a problem with delegates not being transferred when duplicating. Thus I am considering the second method and wondering how bad it would be on performance.

For more information on the problem with delegates when duplicating a prefab read this post.

I am happy to clarify any of the above should you find my explanation lacking.


texts:
I have a car object in my game that has a car location like any other object. It is able to steer with bicycle KInematics and even rotates while it drives from a car heading vector.
Now I need the camera to follow the car. I put the camera position 10 up and 10 behind the car. But I'm confused on where to make the camera look. I tried this:
pseudo code
lookatcamera = carLocation.x + 5 * cos(carHeading), carLocation.y, carLocation.z + 5 * sin(carHeading);


texts: Vertex Buffer Sharing between DirectX11 and Directx9

texts:
In my d3d9 engine i want to take benifit of compute shader of d3d11. So firstly I created a   vertex buffer in d3d11 with D3D11_BIND_UNORDERED_ACCESS and then tried to create the d3d9 vertex buffer with the Handle.
like

D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.ByteWidth = sizeof(stVertex) * 100;
bd.BindFlags =   D3D11_BIND_UNORDERED_ACCESS  | D3D11_BIND_VERTEX_BUFFER   ;
bd.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS | D3D11_RESOURCE_MISC_SHARED;
hr = dev->CreateBuffer(&bd, NULL, &pVBuffer);       // create the buffer
hr = CreateBufferUAV( dev, pVBuffer, &m_pBufOutUAV );

....
HANDLE sharedHandle = NULL;
IDXGIResource* pDXGIResource = NULL;
pVBuffer->QueryInterface(__uuidof(IDXGIResource), (LPVOID*) &pDXGIResource);
pDXGIResource->GetSharedHandle(&sharedHandle);

hr = g_pd3dDevice9->CreateVertexBuffer( 100*sizeof(stVertex), NULL ,
                                  VERTEX::FVF_Flags, D3DPOOL_DEFAULT,
                                  &g_pVertexBuffer9, &sharedHandle ); //ERROR :

which gives error :

  Direct3D9: (ERROR) :Opened and created resources don't match, unable
  to open the shared resource. Direct3D9: (ERROR) :Cannot create Vidmem
  or Driver managed vertex buffer. Will NOT failover to Sysmem.
  Direct3D9: (ERROR) :Failure trying to create Vertex Buffer

After that i tried to create vertex buffer in directx9 first and tries to share that in direct11 but still it gave error.

HANDLE sharedHandle9 = NULL;
    hr = g_pd3dDevice9->CreateVertexBuffer( 100*sizeof(VERTEX), NULL ,
                                      VERTEX::FVF_Flags, D3DPOOL_DEFAULT,
                                      &g_pVertexBuffer9, &sharedHandle9 );
ID3D11Resource*  pTempResource11 = NULL;
    hr = dev->OpenSharedResource( sharedHandle9 , __uuidof(ID3D11Buffer) ,(LPVOID*) &pTempResource11 ); //Error

  D3D11: ERROR: ID3D11Device::OpenSharedResource: Returning
  E_INVALIDARG, meaning invalid parameters were passed. [ STATE_CREATION
  ERROR #381: DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN ]

I am able to share textures but not buffers.please help me here.
thanks.


texts:
I have created a model in Blender. Now i want to read that 3D model in my c++ program. I figured that a model can be exported to various file formats e.g. .obj, .3ds or COLLADA and then can be read in a c++ program. I have been searching web for doing that for quite a while and found many tutorials. But i ran into issues with most of them. For example, IN the Nehe tutorial they are using glaux which I don't want to use in my program. And the remaining tutorials use md2 which is not supported by Blender.

So can anyone guide me which file format to use for exporting 3D model and how to load that in my OpenGL program? Also how can I animate that model? Is it possible to add extra effects like tone mapping after it has been loaded in the c++ program using OpenGL? if yes then how?

P.S. I am using Linux for game developement


texts:
The problem

I am attempting to use a TEnumAsByte in one of my class headers:

I get compilation errors:

Code sample

I have included everything relevant to the member variable I am trying to create:

Header File:

#pragma region Engine Includes

#include <Containers/EnumAsByte.h>

#pragma endregion

UCLASS( Blueprintable, ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class PLATFORMER_API UGrappleAbilityComponent : public UActorComponent
{
    GENERATED_BODY()

protected:
    // Begin AActor Interface //

    /** Called when play starts */
    virtual void BeginPlay() override;

    // End AActor Interface //

public:
    /** Determines what type of debug draw is used for the continuous grapple scanning */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Grapple Scan", meta = (AdvancedDisplay, DisplayName = "Grapple Cont Scan Debug Draw Type"))
        TEnumAsByte<EDrawDebugTrace::Type> m_GrappleScanDebugDraw;
}

Source File:

UGrappleAbilityComponent::UGrappleAbilityComponent()
{
    PrimaryComponentTick.bCanEverTick = true;

    // Give an initial value to the debug draw mode for the continuous grapple scanning.
    m_GrappleScanDebugDraw = EDrawDebugTrace::None;
}

...

void UGrappleAbilityComponent::GrappleScanContinuous(FHitResult & OutHit)
{
    // Only scan if the player is not attached and their airbrake is not active
    if (!m_GrappleHook->IsAttached() && !m_OwnerCharacter->IsAirbrakeActive()) {

        // Increment the trace lerp value.  -   Then wrap the Trace lerp value back around to 0.
        m_GrappleScanTraceLerp += 0.1f;         if (m_GrappleScanTraceLerp > 1.f) { m_GrappleScanTraceLerp = 0.f; }

        // Calculate the proposed end point of the grapple.
        FVector EndPoint = m_StartPoint + m_StartPointDirection * m_GrappleCastDistance;
        float zOffset = FMath::Lerp(m_GrappleContScanLowHeight, m_GrappleContScanHighHeight, m_GrappleScanTraceLerp);
        EndPoint.Z += zOffset;

        // Perform the box traces.
        UKismetSystemLibrary::BoxTraceSingle(GetWorld(),
            m_StartPoint, EndPoint, m_GrappleContScanHalfSize, FRotator::ZeroRotator,
            UEngineTypes::ConvertToTraceType(ECollisionChannel::ECC_GameTraceChannel5),
            false, {}, m_GrappleScanDebugDraw.GetValue(), OutHit, true);
    }
}

Additional Info

The compilation errors relating to the BoxTraceSingle call are irrelevant as they only occur due to the compilation errors with the TEnumAsByte. Aside from the .GetValue() call. Removing this still causes similar compilation errors however.

I can confirm this as, by looking at Epic's engine code, they use TEnumAsByte in exactly the way I have done here, aside from the .GetValue() call.

What the hell is going on here?


texts: C++: Setup the basic Update function in different classes which all derive from GameObject

texts:
Im working on a little game-framework in c++. Currently i have a (base)class called "GameObject" from which all future in-game objects will derive from.
Class enemy will be class Enemy : public GameObject and class Player will be class Player : public GameObject

This way, i can store all my gameobjects in an array of type GameObject and manage them easily and they will all have the basic game-object variables such as x/y/z coordinates, scale, etc. So what i eventually want is to be able to quickly create a new game-object by creating a new class and then simply inheriting from GameObject.

Know how in Unity every game-object monobehaviour script has a start function and an update method? That's what im trying to recreate, and my teacher has been able to recreate in the past using Java. (except he simply used the constructor instead of a "Start" method)

Here is where my problem comes in: I can't find a way to call the Update() method from all those classes that derive from GameObject. My teacher was able to get this working in a small java framework by putting this for-loop in the main-loop of the program:

if(_gameObjList.size() != null){
   for(int i = 0; i < _gameObjList.size(); i++)
   {
     _gameObjList.get(i).Update();
   }
}

Now im pretty sure that this is the correct c++ equilavent of that code:

if(_gameObjList.size() > 0){
   for(unsigned int i = 0; i < _gameObjList.size(); i++)
   {
     _gameObjList[i].Update();
   }
}

In the GameObject class of that java program there's an empty Update() method, which, if removed will break everything, and offcourse in every class that derives from GameObject there's also their own Update() method which for some reason gets called too, but does not give an error if removed. So this way all Update() methods from all classes that derive from GameObject get called even though from the code, it looks like it's just calling that Update() method from the GameObject class itself and not the classes that derive from it.

So now i wish to use this magic in my c++ program but it doesn't work. It just calls the Update method from the GameObject class and does nothing else :/ It won't call the Update functions of the classes that derive from it.
So perhaps there are any sorcerers online on this forum who can explain this magic to me and how to use it? Or perhaps another way of executing all Update functions without calling all of them specifically?

Sidenote: if in the java program, i change the name of the Update() function in one of the classes that derive from GameObject, it won't be called/executed but doesn't give me any errors either. That specific object just won't be updated anymore.

Sorry for writing all this text, i just want to be as clear as possible.


texts: How to implement a game launch counter in LibGDX

texts:
I'm writing a game using LibGDX in which I want to save the number of launches of a game in a text file.
So, In the create() of my starter class, I have the following code ..but it's not working

public class MainStarter extends Game {

    private int count;

    @Override
    public void create() {
        // Set up the application
        AppSettings.setUp();
        if(SettingsManager.isFirstLaunch()){
            SettingsManager.createTextFileInLocalStorage("gamedata");
            SettingsManager.writeLine("gamedata", "Launched:"+count ,FileType.LOCAL_FILE );
        }
        else{
            SettingsManager.writeLine("gamedata", "Not First launch :"+count++ ,FileType.LOCAL_FILE );
        }

        //
        // Load assets before setting the screen
        // #####################################
        Assets.loadAll();

        // Set the tests screen
        setScreen(new MainMenuScreen(this, "Main Menu"));
    }
}

What is the proper way to do this?


texts: How to circle a target at a constant distance

texts:
I have an AI ship that stops approaching when it gets within firing range, and starts strafing around its target. The problem is that it doesn't circle its target very well. The following code attempts to do this, and for short periods of time, it's convincing, but as soon as you let it run for ~5-10 seconds, the AI ship drifts out of range of the target and is forced into the approach state again.

Vector2 tangent = Vector2.Normalize(new Vector2(TargetVector.Y, -TargetVector.X));
velocity += 0.8f * tangent * accelerationMagnitude * (float)gameTime.ElapsedGameTime.TotalSeconds;
velocity += 0.2f * TargetVector * accelerationMagnitude * (float)gameTime.ElapsedGameTime.TotalSeconds;

The above doesn't work for obvious reasons, so I attempted to bring the target into my frame of reference using the following:

Vector2 tangent = new Vector2(TargetVector.Y, -TargetVector.X);
Vector2 asdf = tangent + (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
velocity += Vector2.Normalize(asdf) * accelerationMagnitude * (float)gameTime.ElapsedGameTime.TotalSeconds;

Here is a quick video on how it behaves using the second method while trying to maintain a firing distance of 350: https://www.youtube.com/watch?v=16Bc46ekJI0  The white line and number indicate the Ship->Station vector and distance, and red circles are the weapon ranges.

How do I make my AI ship circle its prey convincingly?


texts: Organizing objects into groups of 20. C#

texts:
I am building a game where players can build their own airplanes and fly them around. When the vehicle is spawned, all the buildables used to construct the airplane should be placed into groups of 20 to be merged as a submesh to the airplane. When one of the buildables is hit by a projectile and is destroyed, the mesh is reloaded, this time without the buildable that was hit creating the illusion that it was destroyed.

I have a few scripts

Airplane Core:

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

[System.Serializable]
public class AirplaneCore : MonoBehaviour {

    public GameObject airplaneCore;
    public List<AirplaneBuildable> buildables;
    public List<AirplaneChunk> chunks;

    void Start () {
        AirplaneChunk[] airplaneChunks = airplaneCore.GetComponentsInChildren<AirplaneChunk> ();
        foreach (AirplaneChunk chunk in airplaneChunks) {
            chunks.Add (chunk);
        }
    }
}

AirplaneBuildable:

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

[System.Serializable]
public class AirplaneBuildable {
    public string buildableName;
    public GameObject buildableObject;
    public GameObject buildableNormalPrefab, buildableEditorPrefab, buildablePreviewPrefab;
    public Vector3 pos, rot;
    public bool destroyed = false;
    public float health = 100f, maxHealth = 100f;
}

And Airplane Chunk:

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

[System.Serializable]
public class AirplaneChunk : MonoBehaviour {
    public List<AirplaneBuildable> buildablesInChunk;
}

Anyone know a way I can take the buildables from AirplaneCore and place them in groups of 20 and assign each group to an AirplaneChunk's buildablesInChunk list?

For those who don't know, the gameobjects that are in the AirplaneBuilder script are:
-Buildable Object: The actual object representing the component that was placed on the airplane.
-Buildable Normal Prefab: The buildable that is spawned when spawning the plane.
-Buildable Editor Prefab: The buildable that appears on the airplane in the vehicle builder editor.
-Buildable Preview Prefab: Is simply a preview of the buildable and shows what it will look like when placed on the airplane.


texts: Rendering a image with some transparency has removed all black pixels and makes full texture transparent

texts:
I am writing a program where with Directx11 I am rendering a texture to a flat rectangle something along the line a of 2D engine. Now parts of this image need to be transparent, to this effect I looked into alpha blending and it seemed to work until i changed textures and realized that it had removed all black pixels and made the whole image transparent not just those pixels that are blank. So how in Directx11 do you have it so that you preserve the transparency of the original image. I am using a ShaderResourceView that is a loaded png for the texture

**//Setup Blend State
D3D11_BLEND_DESC BlendStateDescription;
ZeroMemory(&BlendStateDescription, sizeof(D3D11_BLEND_DESC));

BlendStateDescription.RenderTarget[0].BlendEnable = TRUE;
BlendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
BlendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;

BlendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC1_COLOR;
BlendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
BlendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
BlendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
BlendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

dev->CreateBlendState(&BlendStateDescription, &blend);
float blendFactor[] = { 0, 0, 0, 0 };
UINT sampleMask = 0xffffffff;

devcon->OMSetBlendState(blend, blendFactor, sampleMask);**


texts: Why when adding a box collider to character i can still walk through the character?

texts:
Like the box collider is not active or exist.
I added a box collider on the left soldier.

I'm using firstpersoncontroller and firstpersoncharacter as player but i can move through the soldier and when the mouse cursor is over the soldier it's not detecting it as "Interactable" object.

The only object that is detecting is the door behind the soldiers. Any other objects are not detecting using the ray cast. So i added a box collider to the soldier for testing but it's not working.

Can't figure out why only the door is detecting.

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

public class CameraRaycast : MonoBehaviour
{
    Ray ray;
    RaycastHit hit;

    void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, 1000))
        {
            if (hit.transform.tag == "Interactable")
            {
                print("Hitted on: " + hit.transform.name);
            }
        }
    }
}


texts: When learning, nothing is better than practice

texts:
A little introduction:

I'm 25, and going to this private french school, CreaJeux, which begins in october. I will be learning mostly game programming, something I wanted to do a long time ago, since the day I wondered how were 3d graphics working on my playstation, when I was 14 or so.

I'm very eager and impatient to begin, and I can't think on anything else (I'm bored), I feel like I'm wasting my time doing nothing, and I wanted to just practice on something during my spare-time, whatever it is.

I'm not a beginner in C/C++, I know how to program, but I didn't make a lot of stuff excepy a little tetris-like with pygame: I just want to make something in 3D, even if it awful and plain ugly, non-accelerated or whatever.

Isn't there anything else than open source 3D engines like irrlicht, panda3d or ogre3d to start something ? Isn't there some game dedicated to modding or dedicated to educate begginners ? Or some projects or practices for begginners like me ? Even simple and ugly 3D seems hard to come by...


texts: (int) Math.floor(x / TILESIZE) or just (int) (x / TILESIZE)

texts:
I have a Array that stores my map data and my Tiles are 64X64. Sometimes I need to convert from pixels to units of tiles. So I was doing:

int x
int y

public void myFunction()
{
    getTile((int) Math.floor(x / TILE_SIZE), (int) Math.floor(y / TILE_SIZE)).doOperation();
}

But I discovered by using (I'm using java BTW) System.out.println((int) (1 / 1.5)) that converting to an int automatically rounds down. This means that I can replace the (int) Math.floor with just x / 64.

But if I run this on a different OS do you think it might give a different result? I'm just afraid there might be some case where this would round up and not down. Should I keep doing it the way I was and maybe make a function like convert(int i) to make it easier? Or is it OK to just do x / 64?


texts: XNA 3D custom shader/effect gives shakey rendering in the distance

texts:
I am rendering a simple flat plane + texture to use as the floor for a game. I'm rendering it using  a custom effect I've written.

The problem I have is that the ground in the distance gets a bit distorted and shakey when the camera moves forwards and backwards.

If I render the same model + texture using the BasicEffect instead of a custom shader it appears smooth and works correctly.

Here's the XNA code setting up the custom effect:

Matrix worldMatrix = Matrix.CreateScale(0.2f);
_floorEffect.CurrentTechnique = _floorEffect.Techniques["Textured"];
_floorEffect.Parameters["World"].SetValue(worldMatrix);
_floorEffect.Parameters["ViewProjection"].SetValue(camera.view * camera.projection);

_floorEffect.Parameters["diffuseTexture"].SetValue(_diffuseTexture);

foreach (EffectPass pass in _floorEffect.CurrentTechnique.Passes)
{
     pass.Apply();
     device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);
}

Here's the shader code:

float4x4 World;
float4x4 ViewProjection;
Texture diffuseTexture;

sampler TextureSampler = sampler_state { texture = <diffuseTexture>; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = wrap; AddressV = wrap;};

struct TexturedVertexToPixel
{
    float4 position : POSITION0;
    float2 textureCoords : TEXCOORD0;
};

TexturedVertexToPixel TextureVertextShader(float4 inPos : POSITION, float2 inTextureCoords : TEXCOORD0)
{
    TexturedVertexToPixel output;
    float4x4 preWorldViewProjection = mul (World, ViewProjection);
    output.position = mul(inPos, preWorldViewProjection);
    output.textureCoords = inTextureCoords;

    return output;
}

float4 TexturePixelShader(TexturedVertexToPixel input) : COLOR0
{
    return tex2D(TextureSampler, input.textureCoords);
}

technique Textured
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 TextureVertextShader();
        PixelShader = compile ps_2_0 TexturePixelShader();
    }
}

Videos to demonstrate what I mean:

Using the BasicEffect http://www.youtube.com/watch?v=matmrIZH-pU
Using the Custom Shader http://www.youtube.com/watch?v=Fu9P4D-UCTc  (see it clearest in 1080p full screen)

Notice the difference when looking at the ground in the distance.


texts:
I'm thinking about using Farseer inside my game (I'm not good in physics), which isn't a bad idea. However something happened while I was thinking about that, I found this tutorial:

http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/

which talks about how to use Farseer, expecially the first part shows how to create a good collision method with a static object (like ground!!!), which, partially answer to my old question:

2D Side Scrolling game and "walk over ground" collision detection

So, is a good idea to use a physics engine to create a "walkable" terrain in a game? (obviusly I will use it for jumps and other things too)
Is it a bit exaggerated, I mean, does it creates performance issues if I use it for something like ground collision which happens all time (except when jumping) in a game?

If it's ok I've solved 2 questions with 1!

Thanks for suggestions.


texts: In an Entity-Component-System Engine, How do I deal with groups of dependent entities?

texts:
After going over a few game design patterns, I have settle with Entity-Component-System  (ES System) for my game engine.  I've reading articles (mainly T=Machine) and review some source code and I think I got enough to get started.

There is just one basic idea I am struggling with.  How do I deal with groups of entities that are dependent on each other?

Let me use an example:

Assume I am making a standard overhead shooter (think Jamestown) and I want to construct a "boss entity" with multiple distinct but connected parts.  The break down might look like something like this:

Ship body: Movement, Rendering
Cannon: Position (locked relative to the Ship body), Tracking\Fire at hero, Taking Damage until disabled
Core: Position (locked relative to the Ship body), Tracking\Fire at hero, Taking Damage until disabled, Disabling (er...destroying) all other entities in the ship group

My goal would be something that would be identified (and manipulated) as a distinct game element without having to rewrite subsystem form the ground up every time I want to build a new aggregate Element.

How do I implement this kind of design in ES System?

Do I implement some kind of parent-child entity relationship (entities can have children)? This seems to contradict the methodology that Entities are just empty container and makes it feel more OOP.
Do I implement them as separate entities, with some kind of connecting Component (BossComponent) and related system (BossSubSystem)?  I can't help but think that this will be hard to implement since how components communicate seem to be a big bear trap.
Do I implement them as one Entity, with a collection of components (ShipComponent, CannonComponents, CoreComponent)?  This one seems to veer way of the ES System intent (components here seem too much like heavy weight entities), but I'm know to this so I figured I would put that out there.
Do I implement them as something else I have mentioned?

I know that this can be implemented very easily in OOP, but my choosing ES over OOP is one that I will stick with.  If I need to break with pure ES theory to implement this design I will (not like I haven't had to compromise pure design before), but I would prefer to do that for performance reason rather than start with bad design.

For extra credit, think of the same design but, each of the "boss entities" were actually connected to a larger "BigBoss entity" made of a main body, main core and 3 "Boss Entities".  This would let me see a solution for at least 3 dimensions (grandparent-parent-child)...which should be more than enough for me.