texts: How to get local point inside a body where mouse click occurred in box2d?

texts:
I need to find out the point inside a body, lets say a rectangular object, where the mouse was clicked on. I'm makin a game where the force will be applied depending on where the mouse was clicked on the body. Any ideas?

Will body.GetLocalPoint(b2vec2) work?  I tried by passing the mouse coordinates when the click occurred when inside the body but if the body's position is (400,300) in world coordinates then for trace(body.GetLocalPoint(new b2vec2(mouseX,mouseY)).x); I get some value between 380 to 406 or something (eg. 401.6666666). I thought getLocalPoint will give something like x=-10 when clicked to the left of the centre of body or x=15 etc when clicked to the right.

Language is As3 btw.


texts: Will making players pay a virtual currency before entering a match discourage them from playing?

texts:
I'm making a multiplayer match-making game, and by my current design, people will need to pay a small fee before joining a match. At the end of the match, the team that won will get the money. That will be a virtual currency, but still, will it discourage people to enter matches? I introduced it to make the matches matter more, because there's always a fear that you will loose your investments.

I'm not talking about anything big here, but even a small amount might have a similar psychological effect as a bigger one.


texts:
I was curious on how hit collision works in games. I know there is a simple method that gives every object in a 2D or 3D world a recengular hitbox that makes it easy to detect a collision, but when rotating object, this becomes complocated. Because simple math can't be used to determine whether two rotated lines cross.

To explain my question I will give you an example of what I mean. If you have two lines: (1, 1, -1,-1) and (2,-2,-2, 2). How do you know if these two hit/cross each other and what if you take a circle with radius 1 and center (0, 0), and a line (2, 2,-2,-2). How would you possibly know if these objects hit or cross each other, also keeping in mind that the performance must be good.


texts:
I'm adding frustum culling into my game engine, but I have some design issues regarding the frustum and the cameras.
Should the frustum be a member of the camera, or vice versa ? Should a camera be built from a frustum or should the camera build and maintain it's own frustum ?


texts: How can I create a pixellated, limited-palette appearance in modern OpenGL?

texts: I wanna get some old art style (256 color, dithering, etc) in modern OpenGL in an effective way. Maybe using a low resolution (320x240) rendered at a bigger space so that the pixels looks "bigger?" I'd just like to fake this old style on modern GPUs.


texts: How does Physics2D.OverlapBoxAll work in Unity 3D?

texts:
I am using Unity to create 2D sidescroller game. In my game I have a person that does a melee attack. In order to implement this I am using
Physics2D.OverlapBoxAll().

The first parameter is the position of the box.
The second parameter is the size.
The third parameter is the angle.
The fourth parameter is the layerMask.

I am having trouble understanding the second and third parameters. What does angle mean? Also I am having trouble understanding the size is relative to which units?

Relevant Code:

My Attack Function:

    void Attack() {
    Vector2 tempx = new Vector2 (AttackTransform.position.x, AttackTransform.position.y);
    Vector2 tempy = new Vector2 (AttackTransform.position.x + swordSwingRange.x, AttackTransform.position.y + swordSwingRange.y);

    Collider2D[] enemies = Physics2D.OverlapBoxAll (tempx,tempy,0,AttackLayerMask);
    Debug.DrawLine (AttackTransform.position, new Vector3(tempy.x,tempy.y, AttackTransform.position.z));
    print (enemies.Length);

}

Explanation: The AttackTransform is the starting position where I would like to instantiate my attack. tempx and tempy are the starting and ending positions respectively. 'enemies' is used to find the the number of colliding objects which i will later iterate to decrease health or something.

In my Debug.DrawLine function it draws a line from the start position to the endposition. Hence shouldn't it draw a line that represents the box that will be formed for Physics2D.OverlapBoxAll() ? However as I have experimented with that it does not so. So what scale of units do the aforementioned methods use?

Another side-question:
Is this the best way to detect collision in front of me? Or is there a better way? Any links would be appreciated I can study up further!

Thank you so much for taking the patience to read my question! And I greatly appreciate the help!


texts: How can I draw filled triangles with the illusion of color?

texts:
So I have used the code of this website for drawing filled triangles. But I would like to improve my game by adding the illusion of color. Well sadly I made my game for the monochrome Nokia 5110 screen which can't draw just one pixel but needs to draw lines. So I though about a concept like that: I could enter a float into my fill triangle function (0-1 = 0-100%) and if I for example enter 0.5 then it will only draw 50% of all the pixels. This would be possible by always leaving a small gap when drawing lines. (I don't care if it starts glitching at for example 1 - 10 percent)

So it turns out that I am just way to dumb to create such an complicated filling method. Is this even possible? Thanks in advance!

Epilogue : You don't really need to create this whole function. Just a little tip or link to an already existing method will help. But thanks if you decide to create it anyway :3


texts: Detect how many blocks can be moved given a grid of blocks

texts:
Let G be a grid of booleans where true means a block is there and false means there isn't a block there.

Let P be the player, which has x and y coordinates and is the size of a block.

G can be accessed with an integer position (ex. (0, 1)) but not with a decimal position (ex. (0.5, 2)). P's position is not guaranteed to be an integer i.e. it could be (1, 1.2) which is in-between 2 blocks.

When the player attempts to move, how do I know the move is possible, and if it isn't possible, how much can we move from the specified move?

Examples

x = 1, y = 0, G[2, 0] = true: In this case no move the right is possible, since the player's right side is touching the left side of the block at (2, 0).

x = -0.4, y = 1, G[1, 2] = true: Here, moving up is impossible since there is a block directly above the player (y goes up as player goes up). But moving 0.4 blocks to the right is possible, so this should be returned by the algorithm.


texts: Moving a character depending on the direction he is facing (C#/Unity3D)

texts:
Right now I have a small soldier on the screen that moves with W, A, S, D and rotates / changes direction with the arrow keys. What I want to happen is when the player's direction changes (by using the arrow keys), pushing W will send him in that direction instead of up the screen.

Also (for example), if you are holding D and the right arrow key at the same time he should move in a circle about a point on the ground (instead of spinning in a circle while moving in a straight line to the right).

Here is my current code:

public class MovePlayer : MonoBehaviour {
  void Update() {
    // Rotate left
    if (Input.GetKey (KeyCode.LeftArrow)) {
      transform.Rotate(0, 0, 1.3f);
    }
    // Rotate right
    if (Input.GetKey(KeyCode.RightArrow)) {
      transform.Rotate(0, 0, -1.3f);
    }
    // Strafe left
    if (Input.GetKey (KeyCode.A)) {
  Vector3 position = this.transform.position;
      position.x -= 0.055f;
      this.transform.position = position;
    }
    // Move up
    if (Input.GetKey (KeyCode.W)) {
      Vector3 position = this.transform.position;
        position.y += 0.043f;
        this.transform.position = position;
    }
    // Move down
    if (Input.GetKey (KeyCode.S)) {
      Vector3 position = this.transform.position;
      position.y -= 0.043f;
      this.transform.position = position;
      isMoving = true;
    }
    // Strafe right
    if (Input.GetKey (KeyCode.D)) {
      Vector3 position = this.transform.position;
      position.x += 0.055f;
      this.transform.position = position;
    }
}

}

Any ideas? Wasn't sure what to search exactly.


texts: I have an image with a bunch of colored regions, with each region corresponding to a province in my game. Each province also has a nation owner, which has a respective color. I need to create a function that, when it is called, changes all pixels of a province's color on the first image and changes them to the owners's color on another image. Should I do this with shaders? A script?


texts: How do I make a scrolling map within an HTML5 canvas?

texts:
My project is a 2D tactics game with a square grid. It's all HTML5/Javascript/JQuery.

I have been able to draw out the grid and have a system where I can load different maps with tiles where units can and cannot move. Now I would like to make it so only a portion of the map is displayed in the canvas and the player can scroll around to different characters and stuff (like in normal tactical games).

However I have no idea even where to get started doing this with an HTML5 canvas. I did something similar in Unity but the level of abstraction with the cameras basically did it for me.


texts:
I tried to create an array Entity[] with elements Human and Zomby.

Entity ent[5];
ent[0].set("human");
ent[1].set("human");
ent[2].set("human");
ent[3].set("human");
ent[4].set("zomby");

or

Entity ent[5];
ent[0] = new Human();
ent[1] = new Human();
ent[2] = new Human();
ent[3] = new Zomby();
ent[4] = new Zomby();
delete[] ent;

They are in different classes because Human and Zomby need different ai functions. They are in the same array to compare them, like this:

for (int a = 0; a < entL; a++)
{
    for (int b = 0; b < entL; b++)
    {
        ent[a].ai( ent[b] ); // process ai interaction with other entities
    }
}

Is there a way for an array to have multiple types,
or is there a better way to handle objects? Here's my example code:

class Entity // base class
{
public:
    float x, y;
};

class Human : public Entity // sub-class
{
public:
    void ai(Entity &n){}
};
class Zomby : public Entity // sub-class
{
public:
    void ai(Entity &n) {}
};

int main(int argc, char **argv)
{
    // create entities in one container
    const int entL = 5;
    Entity ent[entL];
    ent[0] = new Human();
    ent[1] = new Human();
    ent[2] = new Zomby();
    ent[3] = new Zomby();
    ent[4] = new Zomby();

    // inside game while-loop
    for (int a = 0; a < entL; a++)
    {
        for (int b = 0; b < entL; b++)
        {
            ent[a].ai( ent[b] );
        }
    }

    delete[] ent;

    system("PAUSE");
    return 0;
}

RESOLVED

I can make variants of functions in sub-classes like ai using virtual and override.

class Entity // base class
{
public:
    Position pos;
    virtual void ai(Position& other) { }

};

class Human : public Entity // sub-class
{
public:
    virtual void ai(Position& other) override {
        // human-specific AI code
    }
};

class Zomby : public Entity // sub-class
{
public:
    virtual void ai(Position& other) override {
        // zomby-specific AI code
    }
};

Entity* ent[5];
ent[0] = new Human (); // set sub-class elements
ent[1] = new Zomby ();
ent[2] = new Zomby ();
ent[3] = new Zomby ();
ent[4] = new Zomby ();

ent[0]->ai(ent[1]->pos); // call human.ai() passing zomby.pos

delete[]* ent;

Now, an array-pointer of a base-class can store elements of sub-classes.


texts: Model colors look much better in blender than Unity (LWRP), how to fix bad colors in Unity LWRP?

texts:
I made some models in blender 2.8:

After importing them to Unity, they look much worse:

Still the same material as in blender, I use the LWRP and have had nothing but issues with it, the lack of AO being one. Is there something I'm missing because it should not look this much worse in the Game Engine?


texts: How to reduce the time it takes to speed up an object?

texts: I have a body that I am applying a force to every step. However, I it takes a significant amount of time for it to speed up, which I do not want. Is there some value I can adjust to help with this?


texts: Should I downgrade my Unity project to the latest LTS version?

texts:
I created my Unity project with a 2020 version and now I'm using 2020.2.0f1. Recently, I realized that using the latest LTS version is the best choice for games that are in production or about to ship. I tried downgrading to the latest LTS (2019.4.18f1) but since Unity doesn't support downgrading, all my objects disappeared and I got a lot of weird errors in console. My question is:
Should I continue developing the game with the version that I'm using right now or downgrade to the latest LTS version?


texts: Why doesn't games use CORDIC for sin and cos?

texts: If the game devs add CORDIC sin cos calculation to their games, their games will have much better FPS. Why do they use normal sin cos function (e.g. Math.sin) instead of CORDIC?


texts: UPS and FPS - What should I limit and why?

texts:
I'm currently writing a game using C++ and SDL2 and there's one thing that I'm wondering about - does it make sense to limit my frames per second (FPS) and/or my updates per second (UPS)?

I get the idea that if you limit the UPS, you essentially control the speed of the game - if the player moves 1px per update and you always update it 30 times per second, he'll move at a speed of 30px/s and you'll probably also relieve the CPU since the amount of calculations per second decreases. If you limit the FPS, the amount of drawcalls per second decreases, therefore you relieve your GPU. I hope I understood all of that correctly, if not, feel free to correct me.

My question is - what am I supposed to limit in my game? FPS? UPS? Both? Neither? Is there another, better approach to this? How is this done in most games and why?

Answers are greatly appreciated!


texts:
Is there a up-to-date list of WebGL libraries or articals with comparison?
Until now I heard only three.js and GLGE.


texts:
I have a game object called gameObject1 on the screen. It holds an image called red. When I drag an image called  "animal" on  gameObject1 the collision happens correctly and destroys the "animal" in the same layer. Then I increment the score, but when I drag an image called  "animal" on  gameObject2 I want to decrement my score (with out collision). I know the collision on a different is not happening.

 void OnCollisionEnter2D(Collision2D col)
    {

            if(Input.GetMouseButtonUp(0))
            {
        if (col.gameObject.name == "Semi arid" )
        {
            //obj1.rigidbody.isKinematic = false;
                scoreCalculate.currentScore+=10 ;

                Destroy(gameObject);
                //Debug.Log ("Scored1............"+scoreCalculate.currentScore);
                Instantiate(obj1, ObjectSpawnPosition1, Quaternion.identity);
                Instantiate(green, ObjectSpawnPosition1, Quaternion.identity);
                obj1.renderer.enabled = true;
                green.renderer.enabled = true;}


texts: XNA 4.0 problem Initializing Instanced Classes in for loop

texts:
Okay so this is kind of weird, I have some code that creates particle.cs instances

 public void AddParticle()
    {
        for (int i = 0; i < Density; i++)
        {
        particle = new Particle();
        Randomnum = new Random();
        Direction = Randomnum.Next(360);
        InitialVel = AngleToVector(Direction);
        particle.Initialize(Texture, Position, 10, 2, InitialVel);
        particles.Add(particle);
        }
    }

When I set a breakpoint on particles.add I can see that the InitialVel is different for each entry in the particles list. When it gets down to the draw function the initialvel is the same in each and every entry in particles list thus they all draw on top of each other.

the wierd thing is when i set the breakpoint at particles.add and f5 through each of the 10 steps of the for loop the game pops up after the break points are done and all 10 particles are going in random directions as intended but without the break points they are stacked on top of one another and the InitialVel are all the same when it reaches the for loop in the draw method.

Emitter.cs
Particle.cs


texts:
Basically it's the sound of a fuse for a bomb, until the timer sends the signal the sound should stop playing and play the explosion sound, but right now only plays once and the stop.
What i did wrong/ what i did missed?
the code i use for the bomb scene:
extends StaticBody2D

func _ready():
    $AnimatedSprite.animation = "bomb"
    $CollisionShape2D.disabled = true
    $BombTimer.start()
    $FuseSound.play()

func _on_BombTimer_timeout():
    $AnimatedSprite.animation = "explosion"
    $CollisionShape2D.disabled = false
    $RemoveTimer.start()
    $ExplosionSound.play()

func _on_RemoveTimer_timeout():
    queue_free()

func _on_Bomb_body_entered(body):
    print("bomb collided with:" + body.get_name())


texts: Binary Serialization of C# for GameObject in Unity?

texts:
I'm trying to serialize a GameObject (with children and textures) using the binary serialization for C#.

It works with many data types but not with GameObject. In the docs it says should be serializable (http://docs.unity3d.com/ScriptReference/SerializeField.html):

  Serializable types are:
   - All classes inheriting from UnityEngine.Object, for example GameObject ....

I've read suggestions of using the asset of UnitySerialization, but that is overkill for me, I just need to store a GameObject on my scene (that will be generated by many users) and load them all in another scene.

This is the code (I'm following this tutorial: http://www.youtube.com/watch?v=J6FfcJpbPXE&feature=player_embedded)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class GameControl : MonoBehaviour {

    public static GameControl control;

    public GameObject drawing;
    public string drawName;

    void Awake () {
        if (control == null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }
        else if (control != this)
        {
            Destroy(gameObject);
        }
    }

    // Use this for initialization
    void Start () {

    }

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

    }

    public void Save ()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/drawing.drawli");

        UserDraw data = new UserDraw();
        data.drawing = drawing;

        bf.Serialize(file, data);
        file.Close();
    }

    public void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/drawing.draw"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/drawing.draw", FileMode.Open);
            UserDraw data = (UserDraw)bf.Deserialize(file);
            file.Close();

            drawing = data.drawing;
        }
    }

}

[System.Serializable]
class UserDraw
{
    public GameObject drawing;
}

Check the Save/Load functions. I'm just trying to store the "drawing" (GamObject), save it and load it. That's all! Is very simple. With other data types it works. But not with GameObject.

This is the (execution) error:

SerializationException: Type UnityEngine.GameObject is not marked as Serializable.


texts:
I have a couple of .fx files from a Shader-Based 2D Shadows example. I want to utilize the same kind of technique with XNA 4.0's Reach profile, which if I understand correctly needs to have HLSL 2.0 shaders. I am not familiar with shaders, so obviously I need to learn HLSL, but what I'm wondering right now is how to tell what shader code is 3.0 and what is 2.0, because I need to port those shaders to 2.0 and utilize them in my project. Can FX Composer be used to know such a thing?

A sub-question - Is it possible that they would not perform well when ported to 2.0? If I want to utilize a similar effect to what is presented in the link, do I need to bump my project up to the HiDef profile and use HLSL 3.0, or should I be able to get away with 2.0?


texts: Adding a new highscore before or after an equal score?

texts:
I'm making a highscores list for my 2048 replica. An entry in the list consists of a name and a score (e.g. "John" and 2100.) When I add a new entry, the code runs through the list and inserts the new entry when the score for the new entry is greater than the currently indexed entry. So imagine this list:

Roman   17000
Sergei  12500
Dean    8000
Andrew  1400

If John was inserted into the list, the new list would look like:

Roman   17000
Sergei  12500
Dean    8000
John    2100
Andrew  1400

The question is, what do I do when inserting the entry for "Steve" whose score is 8000. Does he go before or after Dean? Is there a convention for this?


texts: How to alter the angle of texture projection

texts:
I'm currently working on a 3Dish game; it's on a grid, with 3D props and the camera looking down on the grid at about 45º, but I want to use 2D sprites for the player and NPCs.

Currently, I'm using a quad as a canvas, but I've run into some problems. If the quad is coming up vertically from the floor, foreshortening squashes the player. If I tilt the quad to the same angle as the camera (manual billboarding), the player looks fine but will clip through 3D objects to the "north" from the camera on the grid. I've looked into point sprites but it seems like these would have the same problem.

So, tilting the canvas is out. I need the player to be able to go in front and behind things.

My latest and most promising attempt was to turn the vertical-oriented square canvas into a trapezoid, to compensate for the perspective change. (The canvas is 32x32; at a 45º angle it ended up having a top length of 28.14 and a height of 39.68.) This gets me a square canvas again, but the texture isn't right. It ends up slightly squashed; on nearest-neighbour sampling it loses a row of pixels in the middle (on the character where it's noticeable) and gains one somewhere at the top (above the character's head...)

My maths on the trapezoid might not be exact, but this doesn't really seem like the right answer for keeping things pixel-perfect. Is there a way to use that canvas quad as, I don't know, like a window onto another rendering context which would be pixel-perfect?

Context: This is in Python, PyOpenGL and Pygame; the maximum GLSL version my computer can handle is 120 so it's openGL 3-ish but not quite.


texts: Turn-based JRPG battle system architecture resources

texts:
The past months I've been busy programming a 2D JRPG (Japanese-style RPG) in C++ using the SDL library. The exploration mode is more or less done. Now I'm tackling the battle mode.

I have been unable to find any resources about how a classic turn-based JRPG battle system is structured. All I find are discussions about damage formula. I've tried googling, searching gamedev.net's message board, and crawling through C++-related questions here on Stack Exchange. I've also tried reading source code of existing open source RPGs, but without a guide of some sort it's like trying to find a needle in a haystack.

I'm not looking for a set of rules like D&D or anything similar. I'm talking purely about code and object structure design. A battle system asks the player for input using menus. Next the battle turn is executed as the heroes and the enemies execute their actions.

Can anyone point me in the right direction? Thanks in advance.


texts: In a multiplayer game, should I store the list of character names on the Player class?

texts:
I am writing a multiplayer game that has account system and character creation system like standart MMORPGs. I have a question about name creating issue. I think that I can create a static variable on Player class that keeps created player names but it confused me. It will tell me name is valid or unvalid depends on the other players has this name.

Questions;

Does implementation does make sense ?
If i have 1000 players, is it means it consumes 1000 times of memory of this list? Or it just consume as like there is one?
What is your suggestion for place that I can keep player name list? A new class?


texts: What's wrong with my line segment plane intersection code?

texts:
I'm following the algorithm on on this website for my line segment intersection test code. But when looking at my line segment and plane intersect it doesn't produce the correct point of intersection.

Here is an example of what I'm talking about.

Here is my code for the test

public static bool SegmentPlane(Vector3 p1, Vector3 p2, float distance, Vector3 normal, out float time, out Vector3 point)
{
    time = 1f;
    point = Vector3.zero;

    time = (Vector3.Dot(normal, normal * distance) - Vector3.Dot(normal, p1)) / Vector3.Dot(normal, (p2 - p1).normalized);
    if(time >= 0f && time <= 1f)
    {
        point = p1 + time * (p2 - p1).normalized;
        return true;
    }
    return false;
}

Display Code

public void OnDrawGizmos()
{
    plane = new Plane(transform.forward, transform.position);

    colliding = CollisionLibrary.SegmentPlane(p1.position,p2.position,Vector3.Distance(Vector3.zero,transform.position),transform.up,out time,out point);

    if (!colliding)
        Gizmos.color = Color.yellow;
    else
        Gizmos.color = Color.red;

    Gizmos.DrawLine(p1.position, p2.position);
    Gizmos.DrawSphere(point, .1f);

    Gizmos.color = Color.white;
    Gizmos.DrawLine(transform.position, transform.position+transform.up * 100);

}


texts:
Here I am again with my ray tracer for ipad. Now I'm trying to add glossy reflection to an object. How do i implement it?
I read some documentation online like these:

http://www.cs.cmu.edu/afs/cs/academic/class/15462-s09/www/lec/13/lec13.pdf
http://www.cs.cornell.edu/courses/cs4620/2012fa/lectures/37raytracing.pdf

If I understood correctly instead of trace a single ray as for standard reflection I have to trace n ray in a random direction. How do I get this random direction for each ray? How do i generate these samples?


texts: LibGDX collision detection on moving and rotating object (rectangle enemy)

texts:
i am trying to get collision dectection working properly but when i do it, the collision area keeps moving. no matter what i tried.
there are 2 objects and the objects are moving and i cannot get the area of the collision to follow the enemy/object.

i am using the method below to see if the collision will work and it does not follow the enemy properly.

enemy class extends sprite {

the above is an example of how i am using the sprite extension.

the object/enemy is a sprite from libgdx the class is extended by sprite.

shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);

shapeRenderer.rect(rect1.getX() + (rect1.getWidth() / 2), rect1.getY()  + (rect1.getHeight() / 2) - 2, rect1.getOriginX() - 1, rect1.getOriginY() - 4, 1.0f, 1.0f, rect1.getRotation());

shapeRenderer.rect(rect2.getX() - 10, rect2.getY() - 10, rect2.getWidth() - 10, rect2.getHeight() - 10, rect2.getOriginX(), rect2.getOriginY(), rect2.getRotation());

shapeRenderer.end();

this is in the enemy class collision check

rect.set(getX() + (getWidth() / 2), getY()  + (getHeight() / 2) - 2, getOriginX() - 1, getOriginY() - 4);

this is to see if the enemy is colliding

public boolean collides(Ball ball) {
 if (getX() < ball.getX()) {
 return (Intersector.overlaps(ball.getRect1(), rect));
  }
 return false;

 }

Any help will be really nice.
thank you


texts: How to detect unknown forces on pool re-used rigidbody?

texts:
I have a ragdoll which performs dying quite well when it is initialized. But when the same prefab object is re-used by being pooled and recycled, it jerks violently when die. As if some forces were left on the rigidbodies when the mesh is disabled.

My code goes through the rigidbodies in the ragdoll and sets isKinematic when the enemy is alive and does his usual animations, but turns isKinematic false when the enemy dies so that ragdoll can take over.
From there the pool's lifetime kicks in giving the corpse sometime to be a ragdoll, then the whole gameobject is disabled and pooled.
When a new enemy is to generated the pool is asked for one and it is provided. The enemy enters the game normally and performs it's animations correctly.
This is where the problem occurs, when the enemy is killed a second time it "jerks" upward as if collapsing in on itself.

The only thing I could think of it that there are some forces left on the mesh when disabled and they activate again when the ragdoll is enabled through death.
So I went through all rigidbodies and do:

rigidbody.angularVelocity = Vector3.zero;
rigidbody.velocity = Vector3.zero;

But this doesn't also work, so I'm not sure if it's remnant forces or even if there's such a thing.

What else could be effecting the gameobject to cause a sudden jerk in the ragdoll, which supposedly doesn't have any forces applied on it's inception?


texts: Change object's location at instantiated moment

texts:
I'm trying to instantiate object(scene) and set it's spawn position at the spawn time. Here's the code I wrote:

func spawn_asteroid():
    var spawn_position: Vector3 = get_spawn_position()

    var asteroid_instance = asteroid_scene.instance()
    asteroid_instance.transform.origin = spawn_position
    spawned_asteroids.append(asteroid_instance)

    add_child(asteroid_instance)

asteroid_scene is PackedScene, so get instance first, and then update it's position, and finally use add_child to append current scene's tree.

It seems fine to me, however when I run the game, the object was spawned at (0,0,0) and then move spawn_position.

I changed it's position before it appended to scene, but why it still (0,0,0) and right after move to the specified position?

In Unity, change object's location right after instancing works. In Godot Engine, is this approach invalid?


texts: GLSL Shader not compiling (Android & LibGDX) and no log available

texts:
I'm trying to get a "ripple"-shader working for OpenGL ES 2.0+ (using LibGDX).

However, I can't get it to compile, and for some reason ShaderProgram.getLog() returns an empty string even though the Shader didn't compile.

I am 100% confident that the vertex shader is correct.. here's the fragment shader (not written by me, but I modified it a bit long time ago.. when I had a desktop project - and it worked back then):

                #version 120
                precision mediump float;
                varying vec2 v_texCoords;
                uniform float time;
                uniform float alpha;
                uniform float waveLengthMultiplier;
                uniform sampler2D u_texture;
                void main()
                {
                    vec2 center = vec2(0.5, 0.5);
                    vec2 tc = v_texCoords.xy;
                    vec2 p = -1.0 + 2.0 * (tc - offset);
                    float len = length(p) * waveLengthMultiplier;
                    vec2 uv = tc + (p / len) * cos(len * 12.0 - time * 4.0) * 0.03;
                    vec3 col = texture2D(u_texture, uv).xyz;
                    gl_FragColor = vec4(col, alpha);
                }

I'm still not very well-versed with shaders, as I've used them only a little.. Like I said, getLog() returns an empty string, so I'm hoping someone spots an error in the code.


texts: Is there a way to read unity console outside of unity?

texts:
my unity  project keeps crashing and it does not let me read the exception error, I am wondering if there is a way to read the unity console externally outside of unity. Any pointers will be highly appreciated.
Thanks


texts: What advantages are there to the one-port-per-client approach for a multiplayer server?

texts:
There are a few older games (Quake III and Hexen II to name a couple) where the server assigns a port per player.

Are there performance advantages to this? I suspect there may be, since Carmack & Co.'s endeavours tend to lean in that direction.

I found this, which doesn't provide many different points of view... unfortunately the Book of Hook (link therein) has been down of late, and I don't know if it will ever become available again. What a waste of valuable oldschool knowledge. (If anyone knows where else this might be available, I would be indebted.)


texts:
My game has a Pokemon-type movement mechanic.

I would like my level was a pitch black level, but the player having a candle can lighten a circular area, and so walk without being able to see more than some near steps beyond him. I.e. not being able to see the whole map.

How can I acheve that in Gamemaker Studio?

Elements in my game:

A character, moving squarely tile by tile.
A wall. Just a wall.
A background for the floor.

The game is not about Pokemon, but think as if I'm using the same mechanics for movement. It also happens to be the same concept as the flash HM in a cave.


texts: I am trying to create Vector2 which starts from the players sprite and points towards other point. And I need its starting point to move along with player sprite. But however whatever I do all my vectors start from the origin and point towards the point I want. Is there any way to make Vector2 to start from the


texts: Using VMs for game development or physical machine?

texts:
When I was doing web development, I would develop websites inside my virtual machines, which had all tools and packages downloaded on them and ready to go. I quite liked this approach to development since I didnt have to clutter up my Host OS with a bunch of different packages and other other software only needed for development.

So for game development, given its focus on speed and much higher demand for system resources, is developing in VMs viable? Or are there any gotcha's or other difficulties when using VMs that could deter someone from developing and testing a game within a VM vs directly on the physical computer hardware? Mainly wondering about speed and if the extra abstraction layer of a VM would cause any significant slow down of game testing (having slower or wonky FPS or things of that nature)?

EDIT: Also, for more info, I'm currently developing on my windows 10 PC with a core i7 processor. I can switch to the built in hypervisor (hyper-v) at any time.


texts:
Context

I'm building a 2D game from scratch in JS.
I'm drawing the map by using rpgmxp tilesets for the moment just to have some resources :

Each tile is 32*32 pixels. I'm using canvas API with ctx.drawImage method to display it :

ctx.drawImage(tile.tilesetImg, tile.sX, tile.sY, this.tile.w, this.tile.h, canvasX, canvasY, Engine.Camera.tile.w, Engine.Camera.tile.h);

I use different parameters for the image source size (this.tile.w & this.tile.h) and the image destination size (Engine.Camera.tile.w, Engine.Camera.tile.h).

This has the effect of scaling the game, like that each user have the same map exactly displayed (32 tiles * 24 tiles). The current tile aspect ratio distortion doesn't matter to me for the moment.

The result displayed to the player with a 4:3 ratio :

Problem

When I change window size if I don't keep the ratio 4:3 (because i display always 32 tiles * 24 tiles for the player) one of my tile types causes strange visual artifacts. This happens in chrome and firefox and probably all browsers.

It's strange because all the other tiles are drawn from the same method, but do not exhibit this behavior.  This behavior only seems to occur when the ratio is very different from 4:3.

Here is an example of what I'm talking about.

There is some transparent lines which display the background at the right of each "bad" tile. Note this tile happens to be the first tile from the tileset (first image above).

The same thing happens if height alone is changed, except the line will appear on the bottom instead.

The thing which is again more strange is that if i change the tileset to draw a red line at the right of the first tile :

The transparent line is replaced by the red line when drawing the map :

From debugging (console.log), there doesn't apear to be any reason that tile source size would be 33px instead of 32px, but the artifacting effect makes it seem like this is the case.

Question

I appear to be using drawImage correctly by all accounts, so googled to see if this was a known problem. I was reading the w3 documentation when I found that :  (especially the last note of part 12)

  Thus, scaling an image in parts or in whole will have the same effect.
  This does mean that when sprites coming from a single sprite sheet are
  to be scaled, adjacent images in the sprite sheet can interfere. This
  can be avoided by ensuring each sprite in the sheet is surrounded by a
  border of transparent black, or by copying sprites to be scaled into
  temporary canvas elements and drawing the scaled sprites from there.

Does this explain the problem ?  Does any one know what the problem is more in detail ?

Thank you in advance, best regards.


texts: make a unified image out of many sprites in unity

texts:
i made a customization character system that it has a seperate image UI for every part f body like eyes, hat, ears and...

now i want to make a unified texture out of it to be able to save it as an image file.
how can i do this?


texts: SFML - How do I create an OpenGL context before showing the window?

texts: I want to create an OpenGL context to initialize some assets before actually showing the window with SFML. How can I do this?


texts: Spherical harmonics lighting interpolation

texts:
I want to use hardware filtering to smooth out colors in texels of a texture when I'm accessing texels at coordinates that are not directly at the center of the texel, the catch being that the texels store 2 bands of spherical harmonics coefficients (=4 coefficients), not RGBA intensity values.

Can I just use hardware filtering like that (GL_LINEAR with and without mip mapping) without any considerations?

In other terms: If I were to first convert the coefficients back to intensity representations, than manually interpolate between two intensities, would the resulting intensity be the same as if I interpolated between the coefficient vectors directly and then converted the interpolated result to intensities?


texts: How do you guys handle shading in a 3d game? I have a directional light source that shades one side of a tree made of cubes. The remaining 3 sides all get ambient shading only. So the 3d effect is lost when looking at two ambient shaded sides. Am I missing something? Should I be shading the side furthest from the light source even darker? I tried looking at Fallout 3 and it kinda looks like this is what they do however Minecraft appears to shade a grass mound with two opposite sides light and the remaining two opposite sides dark kinda giving the effect that there are two directional lights for the two light shaded sides and ambient light for the dark shaded sides.


texts: How do I get the position of a static body in Jbox2D?

texts: I'm trying to get the position of a static body in JBox2D, how do I do that?


texts: Download a file from internet using c++ and sdl2

texts:
I am using the SDL2 libs. I want to know how to download an mp3 file from a weblink (from my website) and use it in game (i know how to play songs but not how to download them).
Obviously these songs are not copyrighted..
Can you give me example code using sdl2_net ? Thanks


texts:
I'm building a sort of city building sim and would like the ability for people to automatically place roads (or rail) based on a start and end point and for the sim to calculate the optimal route. I thought this would be relatively easy to do with normal path finding but I'm finding it challenging to deal with impassable obstacles and areas where you really wouldn't want a road/rail unless there was no other option!

See an example below - the difficult terrain might be a swamp or a park which we'd like to preserve if possible and the impassable might be really bad terrain, or something protected - for example a National Park.

I thought about using Dijkstra's algorithm but there is no real set of routes/nodes - as you can see the possible routes are quite open, same with A*. The areas covered would also be quite large so I'm trying to avoid a grid based system - I'm wondering if there is a vector based path finding algorithm? I found this https://faculty.nps.edu/ncrowe/opmpaper2.htm which creates a grid of vectors which looks halfway to what I want, but again could be quite expensive on a large area.

Any suggestions would be appreciated!

Thanks,


texts:
I'm interested in evaluating the different ways that the netcode can "hook into" a game engine. I am designing a multiplayer game now, and so far I have determined that I need to (at the very least) have a separate thread to handle the network sockets, distinct from the rest of the engine which handles the graphics loop and scripting.

I did have one potential way to make a networked game entirely single-threaded, which is to have it check the network after rendering each frame, using non-blocking sockets. However this is clearly not optimal because the time it takes to render a frame is added to the network lag: Messages arriving over the network must wait until the current frame render (and game logic) completes. But, at least this way the gameplay would still remain smooth, more or less.

Having a separate thread for networking allows the game to be completely responsive to the network, for instance it can send back an ACK packet instantly upon receipt of a state update from the server. But I'm a little confused about the best way to communicate between the game code and the network code. The networking thread will push the received packet to a queue, and the game thread will read from the queue at the appropriate time during its loop, so we haven't gotten rid of this up-to-one-frame delay.

Also, it seems like I would want the thread which handles the sending of packets to be separate from the one that is checking for packets coming down the pipe, because it wouldn't be able to send one off while it is in the middle of checking if there are incoming messages. I am thinking about the functionality of select or similar.

I guess my question is, what's the best way to design the game for the best network responsiveness? Clearly the client should send user input as soon as possible to the server, so I could have net-send code come immediately after the event processing loop, both inside of the game loop. Does this make any sense?


texts: Libgdx change color of Texture at runtime

texts:
I've also asked this question on StackOverflow.
In a Libgdx game, I have some Animations for my Player. All the Frames for this Animation are inside a TextureAtlas. The Player Textures show a human, with a white T-Shirt. The T-Shirt is the only white part of the Player.
Now i want to be able to replace the white color with red for Player1, with green for Player2 and so on. How can I do that, without losing the advantage of the TextureAtlas (Texture switching)?
Of course 1 way would be to store 4 versions of every Frame, for 4 different Players (colors). However, there are games out there where you can fully customize the Player, give them a blue hat, red pants, and pink shirts and so on. How can this be done?


texts: Invert parent transform (doesn't work for combination of rotation and scale)

texts:
My problem
I'm working with Qt3D and my problem is almost exactly like this one:
https://stackoverflow.com/q/60995155/3405291
Suggested solution
A solution is suggested here:
https://stackoverflow.com/a/61315454/3405291
Understanding the solution
I have a problem understanding the suggested solution. Specifically:

The problem is that the QTransform node does not store the transformation as a general 4x4 matrix. Rather is decomposes the matrix into a 3 transformations that are applied in fixed order:

S - a diagonal scaling matrix
R - the rotation matrix
T - translation
and then applies it in the order T * R * S * X to a point X.

So when the transformation on the parent is M = T * R * S, then the inverse on the child will be M^-1 = S^-1 * R^-1 * T^-1. Setting the inverse on the child QTransform will attempt to decompose it in the same way:

M^-1 = T_i * R_i * S_i = S^-1 * R^-1 * T^-1

That doesn't work, because particularly S and R don't commute like this.

I'm looking for the phenomenon happening here and why it happens. Does it happen in other 3D engines? How is it resolved in other 3D engines?


texts: Unity: Hiding Game Objects vs Creating them

texts:
My game project involves collecting items that will be displayed in trophy cases of sorts.

There could be several hundred objects as the scale of the project increases, each with their own position, rotation and scripts.

I would find it easier to place the assembled items in their correct location using the editor and set their canvas group alpha to 0 (and set booleans in the script to inactive etc) and 'activate' them when they are 'collected' rather than instantiate them from prefabs as GameObjects.

My main question is about performance, is it costly to have my Gameobjects set in scene & created but set to 0 alpha? I don't need these objects to move or be destroyed etc.

My second question is about best practices for architecture design, is this a horrible way to do things? is a workaround for instantiating prefabs just lazy and counterproductive?


texts:
I have an issue where my game suddenly stops for a second and then continues. And I think it has something to do with my performance so I took at look at the profiler:

I tried to take a screenshot as soon as the crack happened:

However, since I am a bit new to optimization could anyone give me a helping hand on what might be the problem here?


texts: Tweening back from arbitrary 3D rotation in javascript

texts:
I'm using a 3D javascript library to rotate the vertex of a 3D object with a classic 3x3 matrix, to an arbitrary angle in the 3D space, as depicted in the image below.

For example, a first rotation of 180° about the X axis, and a 2nd rotation of 180° about the Z axis will produce the following result:

Now, i need to tween back the 3D object to the initial rotation, e.g. to 0,0,0 degrees.

Briefly, the 3D figure  shall be return to its initial position.
In this example, the shortest way would be to apply to the figure a 180° rotation about the Y axis.

How can i determine the shortest way, starting from an arbitrary rotation, and then calculate a certain number of intermediate rotation angles to smoothly animate the movement of the 3D figure?

Is this a problem of decomposing a rotation matrix back to Euler angles, or could be this accomplished with pure matrix math?  Should i keep track of the applied rotation angles?  I have really no idea from where to start.

Any hint, preudocode or javascript algorythm that can me point to the right direction would be greatly appreciated!


texts: What do I need in order to receive payments from Valve?

texts:
I'm developer from Russia and I recently passed Steam Greenlight.

Now I'm stuck on the Valve program enrollment phase. From what I've seen in the Valve forms, it is not necessary to create a company, such as LLC, there is 'Sole proprietor' option here. So I decided to choose this.

The questions were easy, but then I bumped into two stoppers: information about my bank account and information related to taxes.

As for taxes, I think I understand what to do. I need to apply for EIN in IRS and then fill the form W-8BEN.

But bank account is the different beast. I cannot decide, which type of bank account to use. Will it be suffice to create simple bank account, like this you use in your everyday life? In which currency this account should be? In Russian roubles or in US dollars? Roubles are preferable to me, but it's not a problem to create USD bank account. I simply cannot decide which is better.

It will be great if some non-US (and maybe US too :) ) indie dev shared some knowledge about this. Again, my most important questions:

1) Are you using the 'Sole proprietor' option without creating any form of company? Is this indeed legal and acceptable?

2) Can you use ordinary bank account for the purpose of receiving payments from Valve? If yes, in which currency is this account of yours?

Please answer only if you are absolutely sure about it, e.g. you already using this scheme and received at least one payment from Valve.

Thanks in advance!


texts: 2d coordinates vs x/y screen positioning

texts:
I have a 2d top-down view tile map game, that generates random color tiles (water colors) as you move the character. I've been positioning elements on screen using the x/y coords (finding a way to generate new tiles as the player moves was no picnic, but I did it).

My problem is that I want to establish an actual map-level coordinate system, so the player knows where they are. I'd prefer to just count a first "spawn" area as 0,0 and then count from there.

How should I handle doing that? The problem with x/y is that it's relative to the window frame. I have code that detects when the character reaches the edge of the window, and it "freezes" the player, and moves the map instead.

Whatever system I use, I'll need to be able to add code that can check for other nearby entities.


texts: Identify an object currently selected in the game

texts:
I am making a 2D isometric game that uses the mouse. When I left click on an object, this object should be selected, but how do I determine what object that's currently selected and show a halo around it?

My objects are stored in a list of game objects as std::vector<Game_Object *> Object_Game. I am using the SDL library with C++. I did some research on Google but only found articles about Unity. Can someone help me with this?


texts: How do I center a sky sphere on the camera?

texts:
I'm trying to render a sky using D3D 11. What I have seen in tutorials so far uses cube mapping, which I don't want to use. I want to create a sphere, texture it, and center that sphere on the camera, but I don't know how to do the last part.

How do I center it around the camera?


texts: How to associate multiple arrays of vertex data and uv data with an attribute? OpenGL ES

texts:
I create the buffers to to put on them the vertex data and uv data:

    ByteBuffer bb = ByteBuffer.allocateDirect(coord.getVertices().length * 4);
    ...
    vertexBuffer.position(0);

    ByteBuffer dlb = ByteBuffer.allocateDirect(coord.getIndices().length * 2);
    ...
    drawListBuffer.position(0);

    ByteBuffer uv = ByteBuffer.allocateDirect(uv.getUv().length * 4);
    ...
    uvBuffer.position(0);

Then I pass this vertex data using these buffer to shader with:

glGetAttribLocation(Shader.program_Image, Shader.V_POSITION);
...
glVertexAttribPointer(v_Location, 3, GL_FLOAT, false, 0, vertexBuffer);

and the uv data with:

glVertexAttribPointer(a_Location, 2, GL_FLOAT, false, 0, uvBuffer);

This allows me to render multiple shapes using ONE array, and I also can use a texture atlas and load a special of "multiple-texture", and at this point my app run correctly without any error, but I want to do now is have different arrays and send them to shader, to be able to transform only some arrays, I don't know if this is possible, for the moment I have tried without success, and I was thinking if there is a way to add all the arrays to the same buffer and how to do it.


texts: I can not proceed to my room menu using photon in unity when i use PhotonNetwork.JoinRoom()

texts:
I have a TextMeshProUGUI called EnterRoomName and I am trying to enter the name of the room that I'm supposed to enter, but it's not working.
This is my function:
public void JoinRoom()
{
     PhotonNetwork.JoinRoom(EnterRoomName .text);

     MenuManager.Instance.OpenMenu("loading");
}


texts: How to make a script work when clicked only on the given prefab?

texts:
I am very new to unity but not to C#.

I am working in Unity 2D

I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable.

So how do I make a script work only when clicked on that specific prefab


texts: Prefab Instantiates into scene, but when I store a reference to the instance it's null

texts:
I am instantiating and parenting two objects - the first is a Unity primitive and the second is a prefab cube (literally nothing but a cube made into a prefab). The direct instantiation of the primitive works great, but when I try to instantiate the prefab I get NullReferenceException:Object reference not set to an instance of an object

Below is my script:

    Vector3 myPosition = new Vector3 (x, Rotator_Prefab.transform.position.y , z);
    GameObject ball = GameObject.CreatePrimitive (PrimitiveType.Sphere);
    ball.transform.parent = gameObject.transform; // no problems and gameObject.name gives me the right parent

    GameObject prefab = Instantiate (Rotator_Prefab, myPosition, Quaternion.identity) as GameObject;
    prefab.transform.parent = gameObject.transform; // this gives me an error

The error is coming from the prefab still being null after being instantiated. Still it shows up in the scene. Would anyone have any ideas ?
- Thank you!

Update: Where the prefab is coming from


texts: Unity: UNetWeaver warning: SyncVar set from within property function. This will not set dirty flags. How to?

texts:
I was trying out the new Unity networking and I added the SyncVar attribute to one of my variables to be synced. I also have a property to get/set the variable and update the visuals when set. I set the "hook" variable in the SyncVar so the property is used and visuals are updated properly (or that was the idea, since it gives an error :P)

[SyncVar(hook = "set_Tapped")]
private bool _tapped;
public bool Tapped
{
    get { return _tapped; }
    set { _tapped = value; UpdateRotation(); }
}

Now however I get an error in the console:

UNetWeaver warning: SyncVar [_tapped] set from within property function [System.Void Card::set_Tapped(System.Boolean)]. This will not set dirty flags.

How should this be handled? I could just make a set method myself (not using properties), but is there a better/nicer way?

Thanks!


texts: Viewing one of multiple worlds in a component entity system?

texts:
I've been working on a space simulation game.  The player can control a ship and fly through wormholes to get from one solar system to another.  I would like the player to be able to switch the camera view between the different solar systems they own something in (world, factories, defenses, etc).

If am using just one component entity world then how do I tell the rendering system that looks for sprite components to only draw the sprite components of one solar system?

I could add a "solar system id" field to each sprite component and have the rendering system check each component before rendering to make sure it's in the "active" solar system.  It doesn't seem like a good idea though.  Mostly because I'd be adding another if case before processing every single sprite, at the very least (other components may need similar checks).

I could have the rendering system maintain an internal map of which solar system contains which entities, but then I have to write entity systems that keep track of all the entities, which is my entity system framework's job (Artemis for Java).

Currently I am planning on making all of the solar systems separate from each other.  They wouldn't exist in the same coordinate system.  I suppose I could instead put everything on the same coordinate system and just move the camera around based on which solar system the player wanted to view at that time.  The problem with that would be that my sprite rendering system would still be looping through all the sprites in the game, instead of just the ones at the active solar system.

So, for lack of better options, I'm leaning toward using multiple component entity worlds.  So each solar system would get its own set of systems (including the rendering system), and I'd set which one was active to enable the rendering systems for that solar system.

I didn't want to take this approach for two reasons.  First, it adds another layer of complexity on top of everything.  Second, it seems like it might lessen some of the performance benefits (caching) of looping through all the same types of components and running the same entity system algorithm.  Instead of doing a breadth-first loop through all the components it would be more of a depth-first loop through all the systems' components.

So what is the best way to handle this?


texts: Is it legit to use Custom Controller Buttons for PC Games in Unity?

texts: Not sure if this is off topic, but I have a problem. I'm making buttons for my own controller in my Game. For example, the attached images will appear to indicate the player to press the A or B Buttons. The image resembles Xbox Controller Buttons. So, is it legit to use them as Buttons of my own Custom Controller?


texts: Monitor external window events with SDL2

texts:
I'm trying to render my game (SDL2, C++) in a Windows Form application (C#) using C++/CLI to interface with my underlying C++ code. The purpose of the form is to create an editor which can monitor/adjust/interact with the game, however the game is also executable without the form.

To do this I'm using the SDL_CreateWindowFrom function (which takes the handle  to the form panel). This works fine for actually rendering to the panel, however I'm not receiving any events when calling SDL_PollEvents. When I use SDL_WaitEvent instead I do receive SDL_SYSWMEVENT's but this isn't ideal (as this means my renderer will be stalled while waiting for events AND I would have to process raw windows message events (e.g. WM_KEYDOWN)).

Is there a way to allow SDL to receive (particularly important: input) events from an external window? Is there a way to override the WndProcHandler that SDL uses? Or is there an entirely different approach I should be taking?

Thanks a lot!


texts:
I'am using the current mouse position to aim the player sprite, but I am not getting the best results. I want my sprite to have the direction pointed wherever my cursor is in the screen.

Here's my code:
My update method

public void update(float dt){
    time += dt;
    float yInput = (Gdx.graphics.getHeight() - Gdx.input.getY());
    vec.set(Gdx.input.getX() - position.x, yInput - position.y).nor();
    //position is a Vector2 update sprite coordinates
    position.x += vec.x * 15f;
    position.y += vec.y * 15f;
}

and here's my draw method

public void draw(){
    batch.begin();
    sprite.setPosition(position.x - sprite.getWidth()/2, position.y - sprite.getHeight()/2);

    float xInput = Gdx.input.getX();
    float yInput = (Gdx.graphics.getHeight() - Gdx.input.getY());

    float angle = MathUtils.radiansToDegrees * MathUtils.atan2(yInput - position.y, xInput - position.x);

    if(angle < 0){
        angle += 360;
    }
    sprite.rotate(angle);

    sprite.draw(batch);
    batch.end();
}

So what's wrong? why I get bad results?


texts: Unity C#: Using Linecast with collider bounds

texts:
I'm trying to to detect when two 3D objects overlap each other 'visually' without actually touching. For example, if I have two spheres in a scene that are 1 meter apart and I rotate my camera around the objects so that one sphere is blocked by the sphere in front of it, I want to detect when this occurs.

After many searches in this forum, I patched together the solution below. However, it only partially works: it only detects overlap when the center of the occluded object is reached (i.e., "bounds.center"). I read that there is a way to use the bounds in this scenario so that it samples multiple rays from around the object. This way, overlap is detected at the objects visual boundary and not just it's center. Unfortunately, my coding abilities are meager and I can't figure out how to do it.

Any help would be greatly appreciated.

using UnityEngine;
using System.Collections;

public class OverlapCheck : MonoBehaviour {

     public Transform myCamera;
     private Color mouseOverColor = Color.green;
     private Color originalColor;
     private Vector3 objectExtents;

     // Use this for initialization
     void Start () {
         originalColor = gameObject.GetComponent<Renderer> ().material.color;
         objectExtents = gameObject.GetComponent<Collider>().bounds.center;
     }

     // Update is called once per frame
     void Update () {
         if (Physics.Linecast (objectExtents, myCamera.position)) {
             gameObject.GetComponent<Renderer> ().material.color = Color.yellow;
         } else {
             gameObject.GetComponent<Renderer> ().material.color = originalColor;
         }
     }
 }


texts:
I'm starting to make a bubble shooter game for a mobile OS. Assume this is just the basic "three or more same-color bubbles that touch pop" and all bubbles that are separated from their group fall/pop. What data structures are common for storing the bubbles?

I've considered using an undirected, connected graph where each node is a bubble. This seems like it could help answer the question "which bubbles (if any) should fall now?" after some arbitrary bubbles are popped and corresponding nodes are removed from the graph. I think the answer is all bubbles that were just disconnected from the graph should fall. However the graph approach might be overkill so I'm not sure.

Another consideration for the data structure is collision detection. Perhaps being able to grab a list of neighboring bubbles in constant time for a particular "bubble slot" is useful. So the collision detection would be something like "moving bubble is closest to slot ij, neighbors of slot ij are bubbles a,b,c, moving bubble is sufficiently close to bubble b hence moving bubble should come to rest in slot ij".

A game like this could be probably be made with a relatively crude grid structure as the primary data structure. However it seems like answering "which bubbles (if any) should fall now?" would be trickier with this data structure.


texts: Why do KD trees put the median split exactly on a point?

texts:
I've understood that KD tree split points using the median while cycling on each axis. I've also understood that at each node traversal, a nearest search must use a sphere to store to nearest neighbor (in case the query point is very close to the split median).

What I don't understand, is why median are always aligned with one point? Does that mean nodes are always storing one point? Does that mean each node can only have one point and 2 childs nodes ?


texts: How to add caves to a terrain mesh generated with 2D noise

texts:
Am I getting it right, that when I'll make a single mesh that represents terrain using unity's built-in 2D Perlin noise function, then I'll be able to somehow add caves using whatever (Perlin worms for example)?
Or do I need to find solution with 3d noise?


texts: How to use multiple custom vertex attributes in OpenGL

texts:
My code currently uses glBindAttribLocation and glVertexAttribPointer to specify two custom vertex attributes in indices 6 and 7. This seems to work fine, but I wish to add another attribute and no index other than 6 or 7 will work - the shader instead acts like the attribute is always set to a value of 0.

I'm using gl_Vertex, gl_Normal, gl_Color and gl_MultiTexCoord0, and apparently some nVidia thing means indices 0, 2, 3 and 8 are off limits, but that should still leave other indices. I don't use gl_SecondaryColor or gl_FogCoord anywhere in my code or shaders for example, but indices 4 and 5 still don't work.

If I change graphics cards for an ATI one which supports more than 16 attributes, then indices 16+ work fine, but I want to support cards with only 16 attributes.


texts: How can I position framebuffer objects on the screen in OpenGL?

texts:
I currently have two framebuffers which are drawn using

glBlitFramebuffer(0, 0, 1920, 1080, 0, 0, 1920, 1080,
    GL_COLOR_BUFFER_BIT, GL_NEAREST);

But the texture does not take up the whole screen, and I would like to position it at a certain x,y on the screen. The images by default start from 0,0 and then span the width/height provided, however I would like the image to start at say, [100, 100] and span the width/height provided.

How would I do this?


texts:
3D. Given a point mass m, inital position p0 initial velocity v0, and a desired location d, how do I apply forces (with magnitude no greater then fMax) to move m to d and stop. I know how to apply forces, it's the strategy for determining what force to apply each frame.

You would think this would be easy - but it's turned out to be difficult.

A solution that only converges at the limit is not acceptable (i.e. having the mass oscillate back/forth over the destination by smaller and smaller distance)

Edit: This is not the same as this question. Finding the stopping distance is trivial, but is (maybe) only part of the solution.

Edit: Also not the same as this question, because the highest answer is incorrect (as stated by my constraints)


texts: Simultaneous Animation for a GameObject - Unity3D

texts:
Its my second week with Unity. I am doing a 2D game and I have a small GameObject which should change its sprite along with following a definite path defined in Animation Curves.

I did both of them in separate .anim files since the transform animation had many keyframes, i thought it wont be good to put the '2' sprite keyframe repeatedly along side the transform keyframe.

But the problem is, I cant get it both working together at the same time. I dont want any blending because the animation is timed well already.

Also, I tried deleting the sprite change animation and tried it under script changing the SpriteRenderer.Sprite property under Update(); but it works only when the Animator component is disabled in the GameObject.

Any Solutions ? :)


texts: No-duplicate collection without iterator allocation

texts:
Problem

I need a collection with non-duplicate values minimising memory allocation during access operations. I am prepared to compromise with a slight decrease of performance to make up for the improved "garbage generation".

Solutions Considered (including discarded ones for reference)

Extend ArrayList to include a check on add(E e) for duplicates and do nothing if value exists. (this may include other methods too)
Use HashSet (discarded) - iteration of elements causes instantiation of a new Iterator which defeats the requirement of minimal memory allocation during access.
Convert HashSet to ArrayList (discarded) - creates more memory allocaiton than HashSet iteration.

Question

Is the extention of ArrayList to reject duplicate values a sensible way to achieve non-duplicate collection with minimal memory allocation? Are there alternative methods I should consider?

Notes

Most advised solutions to eliminate duplicates in ArrayList I have seen refer to using HashSet or other object instantiation which defeat my minimal memory allocation requirement. The only implementation I can think of is a basic "for iteration" of the ArrayList checking equality of the added value against each existing element.

Class NonDuplicateList extends ArrayList{
    @Override
    boolean add(E e){
        for(int i = 0; i < this.size(); i++){
            if(this.get(i).equals(e)
                return false;
        }
        return super.add(e);
    }
}

For completion this question is being posted on gamedev stackexchange as the game dev community is more sensitive to the subjects of memory allocation and garbage collection impact, so hopefully I won't get comments along the lines of iterator allocation memory allocation is insignificant :-)


texts: Unity WebGL Progress bar never moves but game finishes downloading and works

texts:
Not sure why but the progress bar never moves for WebGL in Chrome, but the game downloads and works?
Using Unity 2020.1.14f1 brotli WebGL builds


texts:
My ad does not appear. I want to click the button and have an ad appear.

using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;

public class GameOverControl : MonoBehaviour {
  InterstitialAd interstitital;

  [SerializeField]
  private AudioSource OverSes;

  void Start () {
    OverSes.Play ();
    MobileAds.Initialize ("");

    RequestinterstitialAd ();
  }

  public void Tekrar () {
    SceneManager.LoadScene ("BonyBony");
    ShowinterstitialAd ();
  }

  public void MenuyeDon () {
    SceneManager.LoadScene ("MainMenu");
    ShowinterstitialAd ();
  }

  private void RequestinterstitialAd() {
    interstitital = new InterstitialAd ("");
    AdRequest adRequest = new AdRequest.Builder ().Build ();
    interstitital.LoadAd (adRequest);
  }

  private void ShowinterstitialAd() {
    if (interstitital.IsLoaded ()) {
      interstitital.Show ();
    }
  }
}


texts: How do you find games with a similar idea?

texts:
I'm thinking about making an indie game and want to know if there's maybe one with similar idea.

I'm not asking about my idea specifically, I just want to know how to find out if a game has the same idea as the one I want to implement.


texts: How can I choose a pathfinding target for a unit group and move the group to that target?

texts:
So I've got some units which should move to a specific position which is given by the player. Currently the units can move there by finding a path with the A* algorithm (to be more precise: A* Pathfinding Library for Unity)

I was wondering what the best way to move the units is? When the player has selected e.g. 20 units, some of them are near each other, some of them are far away from the others, what is the best way to navigate them to a single position defined by the user. Obviously they cannot just all have the same target since they would never reach it when the first unit moved to it. Thus what do I have to do? Do I have to assign different targets to each unit or do I calculate the target position relative to the position they were to each other before?


texts: What is the difference between a game object being disabled and it made inactive?

texts:
I am looking over a script that has a particular function called to disable the script and mark a list for re-structuring:

void Disable()
{
    gameObject.SetActive(false);
    isEnumerated = false;
}

What I am trying to determine is whether it would be better to simply have the code in the OnDisable() function:

void OnDisable()
{
    isEnumerated = false;
}

I found that OnDisable() calls whenever the game object is "disabled" or "inactive", but I am a bit confused on the exact difference between the two. Documentation I have found that references both is only specific in that they are two different cases, where places that offer definition appear to use the two words synonymously.


texts: Does the ClientSizeChanged event disable exceptions?

texts:
If I illegally index into a list in the subscribed ClientSizeChanged() method, no ArgumentOutOfRangeException is thrown. Is this normal behavior ? And if so, when should I expect this behaviour ?

@ Roy T. : You're right in that it is an event which I'm subscribing to as follows :

game.Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);

and here's my event handler addendum (sorry, I don't know how to properly talk about these things) :

    // Event manager that responds to the window size being changed
    private static void Window_ClientSizeChanged(object sender, EventArgs e)
    {
        presentationRegion = GDM.GraphicsDevice.PresentationParameters.Bounds;
        if (currentScreen <= 0 || currentScreen > screens.Count)
            throw new Exception("currentScreen index is out of bounds of the screen list");

        List<int> myIntList = new List<int>();
        myIntList[-2] = 7; // Exception is not thrown here

        screens[currentScreen - 1].UpdateLayout();
        //Game.Window.Title += " WinCSC | ";
    }

I've put in the integer List just to demonstrate the effect. Although I originally noticed it with the screens[currentScreen-1].UpdateLayout() call.

@ Blecki : You are onto it I think. So when I trace the execution, as soon as i index into myIntList with an index of -2 execution breaks out of Window_ClientSizeChanged() and the exception is not caught. And even if I throw my own exception inside Window_ClientSizeChanged() the application continues without the debugger catching it.


texts: How to import the .fbx scene with multiple objects in XNA so that the objects retain their scene position?

texts:
I have a scene that contains mutiple objects. How can I import it in XNA and maintain each object position? Right now I export the scene in .fbx and load it in a model like this:

 cube.model = contentManager.Load<Model>("cub");

But the objects don't retain their position and are all gathered in one point.

I need a method to import all the objects as individual objects but to retain the objects position in the scene. (i.e. I need to import the scene so that I may manipulate the objects and retain their position in the scene so that I shouldn't reposition all the objects by myself)

The objects are not connected, thus there are no bones. They are individual objects, just placed in some positions.

This is my drawing function, the cube is the gameobject.

void DrawGameObject(GameObject gameobject)
{
    foreach (ModelMesh mesh in gameobject.model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.PreferPerPixelLighting = true;
            Matrix b = Matrix.Identity;
            effect.World = b * gameobject.orientation;
            effect.Projection = camera.projectionMatrix;
            effect.View = camera.viewMatrix;
        }

        mesh.Draw();
    }
}


texts: Are there some libraries or example codes, of a camera manager – a tool, that would move camera using some smooth lines (bsplines or similar)? So basically I request an animation to move to a new eye/center possition, and the tool takes care of the rest?


texts: Unity Mobile: How can we safely store our API key?

texts:
We're making an app in Unity. We're building it for Android and iOS.
We also have a server. In order to use our server you need to present our api key for the server.
So, we need to store that key in the build somewhere (eg. APK file)
But how can we put it anywhere where people wont be able to get it?
Eg. they can get the APK and decompile it.
SDKS for unity for facebook and so on, store an api key in the client. What do they do?


texts: Draw a sprite when a key is pressed in LibGDX

texts:
I'm working with LibGDX. How can I draw a sprite when a key is pressed? I have tried with the following, but it doesn't seem to work.

if (Gdx.input.isKeyPressed(Input.Keys.X)) {
    batch.begin();
    sprite.draw(batch);
    batch.end();
}


texts: Which programming language to use for tools?

texts:
I use C++ as my language as choice.  However, I generally use Python to write helper utilities and tools.

My worry is that as my game engine continues to grow it's getting tedious to reimplement some of its features in Python.

There has got to be a better way.

Here are the options as I seem them

Keep on keeping on.
That is often the answer in a cooperate environment.  Maybe it has some merit.
Build bindings for Python (yuck) and have it use pieces of the engine directly.
Start building the tools using C++ instead.
I already use QT in the Python tools to provide a GUI when needed.  It doesn't seem like it'd be that much harder to use QT in C++ instead.  However I'm worried my tool productivity will go down.  I generally strive to apply much less rigidity in tool code than I would in shipping code.

So what is common practice, use the same language for tools, or use a more RAD friendly one?
What if you use a language that differs from the language of the game which do you use?
How do tools interact with the game engine link to it directly or fake it?


texts: How do I determine my games minimum hardware/software requirements?

texts:
With me going it alone in development I only have limited resources at my disposal i.e one pc with which I develop and test the game. so I only know for certain my game works with that setup.

What options have I got in testing the game on the many different hardware/operating system combinations? Its a windows desktop game.


texts: Constant size geometries for glDrawArraysInstanced calls

texts:
In my application I can keep the objects constant sized
            const Graphics::VectorDouble diffVec(dTranslateX - m_CameraTransformOffset.x,
                                                 dTranslateY - m_CameraTransformOffset.y,
                                                 dTranslateZ - m_CameraTransformOffset.z);

            camScaleInv = Graphics::Lenght(diffVec) * 2.0f * tan(fov * 0.5f * PI / 180.0f);

Than I scale my view matrix with  camScaleInv and I think that is very common to do but ,
I have some objects which I draw with glDrawArraysInstanced. I pass the parent surface only once and another array for duplicating the parent surface in different positions.
That causes my "diffVec" to be different and causes me to not being able to use keep same distance logic in CPU side.
Is there any way for me to keep the objects which are being drawn with glDrawArraysInstanced same size either in CPU or GPU(glsl) side.


texts: Why are .xnb files used rather than source files?

texts:
XNA and Monogame are built using a content pipeline, which takes source files (images, sound effects, 3D models, etc.) and converts them to proprietary .xnb files. What's the benefit of doing this as opposed to simply loading source files directly?

To be clear, I'm not asking how to use the content pipeline. Just why .xnb files are used in the first place.


texts: Character sinks into ground when switching animations

texts:
I originally posted this question on the unity forums, but no one answered my question.
Here it is:
Hello, I have been game developing since May and today I finally figured out how animations work in unity!
But as with everything new in developing, I have problems. Let me just be straight with you. I have absolutely no idea what just happened.
I have a gif you what happens. Why does the character sink like that? Here is my gif and animation image

I don't have any scripts or parameters for testing purposes. I just let it switch automatically. Here are my options for the transition:


texts: Inspector does not appear to match actual value

texts: A text object is where the inspector says, but not where I expected it, and not where Debug.Logerror says it is. What I read as my "strengthTextObj.transform.position.x" is -213 in the inspector but transform.position.x is logged as 111. Why might these be different?


texts: Exponential EXP Curve | FIXED TIME -> MAX LEVEL

texts:
I have yet another experience equation question, with a slight twist.

Problem Situation

Player gain experience from Level 1 - 80.

Time to level from Level 1 to 80 grows exponentially.

There is a constant of total hours X (540 hours in this case) to reach level 80.

What equation results in this?

From this, I should be able to balance an approximate Time To Kill Monster + downtime, varying from easy to hard monsters and experience they can give, resulting in same time to Max Level.

Or I could create quests that takes an approximate Time To Completion but rewards the same ratio of experience.

In my opinion this should be the optimum solution to create content that grant the same ratio of experience to time to level.

Thank you.


texts: Unity Network how to move noplayer object from client side

texts:
When i drag a nonplayer object from host, client can see it, but when move the object from client, host player doesnt see any changes. How can i fix it?

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

public class DragObject : NetworkBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;

void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

void OnMouseDrag()
{
    Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
    transform.position = cursorPosition;
}}


texts: Different textures inside and outside a cube in DirectX 11

texts:
I want different textures for the outside and inside of a box (cube).
The image below shows what I want to achieve. It is kind of an open box, where we can see a different texture inside:

I was trying to solve it by checking whether the normal of the face is point towards the view or to inside the screen, that is we are seeing the "back" of the face.
I was also looking into cube mapping, but it does not seem to be the way.
What method should I use to achieve that result?


texts: Per Instance Textures, and Vertex And Pixel Shaders?

texts:
How do you implement per instance textures, vertex shaders, and pixel shaders?

Given:
1. Two different model templates in Vertex Buffer, Square & Triangle
2. Instance Buffer with [n] instances of type Square or Triangle.

How do I add a Texture, VertexShader or PixelShader ID to the buffer data so that HLSL or the InputAssembly can determine which Shader to use at draw time?

A. How do I "Set" multiple Pixel and Vertex Shaders into the DeviceContext, and how do I tell DirectX to "switch" the Vertex Shader that is loaded at render time?

B. How many Shaders of each type, (Vertex, Pixel, Hull, etc), can I associate with model templates in the default Vertex  Buffer?

C. Can I use some sort of Shader Selector in HLSL?

Related C++ Code

When I create an input layout, can I do this without specifying an actual Vertex Shader, or somehow specify more than one?

NS::ThrowIfFailed(
result = NS::DeviceManager::Device->CreateInputLayout(
NS::ModelRenderer::InitialElementDescription,
2,
vertexShaderFile->Data,
vertexShaderFile->Length,
& NS::ModelRenderer::StaticInputLayout
)
);

When I set the VertexShader and PixelShader, how do I associate them with a particular model in my VertexBuffer?  Is it possible to set more than one of each?

DeviceManager::DeviceContext->IASetInputLayout(ModelRenderer::StaticInputLayout.Get());

DeviceManager::DeviceContext->VSSetShader(ModelRenderer::StaticVertexShader.Get(), nullptr, 0);
DeviceManager::DeviceContext->PSSetShader(ModelRenderer::StaticPixelShader.Get(), nullptr, 0);


texts: HTML5 Canvas fillStyle as numbers not text

texts:
When drawing vector graphics in the canvas you set the fillStyle using an rgba string like this...

context.fillStyle = "rgba(255, 223, 191, 1)";

Is it possible to feed in a javascript object instead (or just numbers). Seems silly that I would need to construct a string to feed to this value if I wanted the color dynamic.

context.fillStyle = "rgba(255, 223, 191, " + alpha + ")";

The specification clearly says "a CSS Color string" but it seems crazy. Am I missing something?

http://www.w3.org/TR/2dcontext/#fill-and-stroke-styles

update: I switched to using globalAlpha for this specific example. But still seems crazy.


texts:
We had a long discussion in my company about character-classes. We are building a skill based game where you will eventually need to select 8 to enter a battle. I am a fan of classless systems, I have always felt that they are created to extend your gameplay hours in a fake way.

We reached a few conclusions:

Classes are there to prevent "best build" scenario where everyone plays with optimal (Personally I feel that this is a weak case, You should be able to design a system where there is no win combination without classes)
Classes create variety by offering different style of play (I agree with this but if you have the freedom to combine different skills you can actually create your own class)
Classes make choosing style of play easier to players. Most of the times players play the same type of character in different games. (Damage Dealer, Healer, Thief/Assassin etc.) (For me this makes most sense from all the arguments from above, but why force people to only part of the skills when you could offer them as templates)

Why are character-classes used in game design? Do you agree with the above points? Yes or no, why do you think like that?


texts:
I've been working on application development with a lot of "retained" GUI systems (below more about what I mean by that) like MFC, QT, Forms, SWING and several web-GUI frameworks some years ago. I always found the concepts of most GUI systems overly complicated and clumsy. The amount of callback events, listeners, data copies, something to string to something - conversions (and so on) were always a source of mistakes and headaches compared to other parts in the application. (Even with "proper" use of Data Bindings/Models).

Now I am writing computer games :). I worked with one GUI so far: Miyagi (not well-known, but basically the same Idea as all the other systems.)

It was horrible.

For real-time rendering environments like Games, I get the feeling that "retained" GUI systems are even more obsolete. User interfaces usually don't need to be auto-layouted or have resizable windows on-the-fly. Instead, they need to interact very efficiently with always-changing data (like 3d-positions of models in the world)

A couple of years ago, I stumbled upon "IMGUI" which is basically like an Immediate Graphics mode, but for user interfaces. I didn't give too much attention, since I was still in application development and the IMGUI scene itself seemed to be not really broad nor successfull. Still the approach they take seem to be so utterly sexy and elegant, that it made me want to write something for the next project using this way of UI (I failed to convince anyone at work :(...)

let me summarize what I mean by "retained" and "immediate":

Retained GUI:
In a separate initialization phase, you create "GUI controls" like Labels, Buttons, TextBoxes etc. and use some descriptive (or programmatical) way of placing them on screen - all before anything is rendered. Controls hold most of their own state in memory like X,Y location, size, borders, child controls, label text, images and so on. You can add callbacks and listeners to get informed of events and to update data in the GUI control.

Immediate GUI:
The GUI library consists of one-shot "RenderButton", "RenderLabel", "RenderTextBox"... functions (edit: don't get confused by the Render prefix. These functions also do the logic behind the controls like polling user input, inserting characters, handle character-repeat-speed when user holds down a key and so on...) that you can call to "immediately" render a control (doesn't have to be immediately written to the GPU. Usually its remembered for the current frame and sorted into appropiate batches later). The library does not hold any "state" for these. If you want to hide a button... just don't call the RenderButton function. All RenderXXX functions that have user interaction like a buttons or checkbox have return values that indicate whether e.g. the user clicked into the button. So your "RenderGUI" function looks like a big if/else function where you call or not call your RenderXXX functions depending on your game state and all the data update logic (when a button is pressed) is intermangled into the flow. All data storage is "outside" the gui and passed on-demand to the Render functions. (Of course, you would split up the big functions into several ones or use some class abstractions for grouping parts of the gui. We don't write code like in 1980 anymore, do we? ;))

Now I found that Unity3D actually uses the very same basic approach to their built-in GUI systems. There are probably a couple of GUI's with this approach out there as well?

Still.. when looking around, there seem to be a strong bias towards retained GUI systems? At least I haven't found this approach except in Unity3D and the original IMGUI community seems to be rather .... ..  quiet.

So anyone worked with both ideas and have some strong opinion?

Edit: I am most interested in opinions that stem from real-world experience. I think there is a lot of heated discussions in the IMGUI-forum about any "theoretical weakness" of the immediate GUI approach, but I always find it more enlightening to know about real-world weaknesses.


texts:
I know a lot of logging libraries but didn't test a lot of them. (GoogleLog, Pantheios, the coming boost::log library...)

In games, especially in remote multiplayer and multithreaded games, logging is vital to debugging, even if you remove all logs in the end.

Let's say I'm making a PC game (not console) that needs logs (multiplayer and multithreaded and/or multiprocess) and I have good reasons for looking for a library for logging (like, I don't have time or I'm not confident in my ability to write one correctly for my case).

Assuming that I need :

performance
ease of use (allow streaming or formating or something like that)
reliable (don't leak or crash!)
cross-platform (at least Windows, MacOSX, Linux/Ubuntu)

Wich logging library would you recommand?

Currently, I think that boost::log is the most flexible one (you can even log to remotely!), but have not good performance update: is for high performance, but isn't released yet. Pantheios is often cited but I don't have comparison points on performance and usage. I've used my own lib for a long time but I know it don't manage multithreading so it's a big problem, even if it's fast enough. Google Log seems interesting, I just need to test it but if you already have compared those libs and more, your advice might be of good use.

Games are often performance demanding while complex to debug so it would be good to know logging libraries that, in our specific case, have clear advantages.


texts: I want the game over screen on this super mario bros C++ remake to trigger arduino/batch file

texts:
I found a someone who has listed the source code in C++ for their remake of Super Mario and I would like to know how I could edit the code for the "Game over screen" to trigger my Arduino or batch file (which ever is easier). The link to this source code is below. I'm pretty new but am every interested in getting this done. Any information would help. Thank you so much!
Github project link


texts: Is there a standard camera position / orientation?

texts:
I've come across a need to position a camera for an arbitrary (unknown) scene. The camera can be updated later, but I thought I'd give it a reasonable default, and the thought crossed my mind that there may be a decent "standard" for this.

At the very least, a given modeling program (Maya, 3dsMax, blender...) ships with a default position / orientation for a camera.

A default light would be useful too; is there a similar standard for this?

In the lack of any good suggestions here, I thought I'd try to orient the camera so that an object of approximate diameter of 2 (such as a unit circle) would fit well in the scene and provide a directional light in the direction of the camera.

Edit: while we're at it, what about:

camera FOV / frustum
light color / intensity / etc


texts:
I'm currently working on a twin stick shooter but I encountered a problem when I rotate my player. The rotation snaps to right angles. I'm guessing it's a problem, due to the value that the joystick gives me back. Here is a screen recording, via Giphy.

How do I go about fixing this problem?

This is my code:

 void FixedUpdate()
{

    float hR = gamepad.GetStick_R().X;
    float vR = gamepad.GetStick_R().Y;

    float lastHR = hR;
    float lastVR = vR;
    // This part was added recently in the hope of smoothing the rotation
    float lerpHr = Mathf.Lerp(lastHR, hR, Time.deltaTime * speedRotation);
    float lerpVr = Mathf.Lerp(lastVR, vR, Time.deltaTime * speedRotation);

    PlayerRotation(lerpHr, lerpVr);
}

void PlayerRotation(float h, float v)
{
    rotation.Set(h, 0f, v);

    if (rotation != Vector3.zero)
    {
        currentRotation = Quaternion.LookRotation(rotation);
        playerRigidbody.MoveRotation(currentRotation);
        lastRotation = currentRotation;
    }
    else
        playerRigidbody.MoveRotation(lastRotation);
}

I also tried two other ways, but each time, I got the same results. I tried every way I could think of, with these lines of code. I don't know where else to look.

// Attempt Two
playerRigidbody.transform.rotation = Quaternion.Slerp(p
    layerRigidbody.transform.rotation, currentRotation, Time.time * speedRotation);

// Attempt Three
transform.eulerAngles = new Vector3(0, Mathf.Atan2(v, h) * 180 / Mathf.PI, 0);


texts: Looking for a square-to-hex pixel coords algorithm

texts:
So as the headline suggests, I am looking for an algorithm/algorithms used for square-to-hex and hex-to-square pixel coordinates convertion.

I have an image which looks kinda "interpolated", meaning some pixels are of one colour, while some have a slightly different shade etc. So pixel colour kinda stores offset or whatever. If you're interested, it's here

It has to do with pathfinding, the logical part of map is made of hexmap while the visual part of map is made of squares. Here, size of the square = 1 pixel, same hex size is equal to 1 pixel.

So basically I will be trying to convert an image with hex pixel coords to image with square pixel coords and vise versa.

I'm sorry if this was answered already somewhere, I couldn't find it anywhere.

P.S. I reverse engineered the image, so in binary it was only X and Y coords stored plus a third byte value which I took as a greyscale colour (later compared with another image and it matched)

Image:


texts:
I'm reading a book about AI - Path planning and path smoothing. Yet this book is using c++ code. And i'm coding in c# with the XNA framework.

I have a path smoothing working, yet the book says it can be more precise (but being a bit slower).

This is the code i have until now:

    public static LinkedList<Vector2> SmoothPathEdgesQuick(LinkedList<Vector2> path, Player player)
    {
        LinkedList<Vector2> newLinkedList = new LinkedList<Vector2>();
        List<Vector2> toBeDeleted = new List<Vector2>();

        var edge1 = path.First;
        var edge2 = path.First.Next;
        while (edge2 != null && edge2.Next != null)
        {
            if (player.CanWalkBetween(edge1.Value, edge2.Next.Value))
            {
                toBeDeleted.Add(edge2.Value);
                edge2 = edge2.Next;
            }
            else
            {
                edge1 = edge2;
                edge2 = edge2.Next;
            }
        }
        foreach (var vector2 in path)
        {
            if (toBeDeleted.Contains(vector2))
                continue;
            newLinkedList.AddLast(vector2);
        }
        return newLinkedList;
    }

And this is working as it should work.
But the book says it can be more precise by using this code:

void Raven_PathPlanner::SmoothPathEdgesPrecise(Path& path)
{
  Path::iterator e1, e2;

  e1 = path.begin();

  while (e1 != path.end())
  {
    e2 = e1;
    ++e2;

    while (e2 != path.end())
    {
      if ( (e2->Behavior() == EdgeType::normal) &&
            m_pOwner->canWalkBetween(e1->Source(), e2->Destination()) )
      {
        e1->SetDestination(e2->Destination());
        e2 = path.erase(++e1, ++e2);
        e1 = e2;
        --e1;
      }

      else
      {
        ++e2;
      }
    }

    ++e1;
  }
}

Somehow i don't know how to update my original code to the one below to make my pathsmoothing more precise.


texts: Using multiple sprite sheets for same object AndEnginge

texts:
I have multiple sprite sheets for my object(Parrot) like eating, moving left to right, right to left and much more. I am using AndEngine gles2.0. How should I implement it? Every time I have to use different sprite sheet, detach previous one and on same location add new one. This is going to be hectic!

Anyone here who already implemented this kind of scenario? If I use single sprite sheet for every animation it size will increase and it will throw a exception of out of memory!


texts: How to rotate an object along its trajectory path?

texts:
I have a missile launcher that uses initial velocity for the trajectory. I edit the launch angle from the editor, and then the script calculates the initial velocity required to land the missile to the target location. The inputs for the calculation are

Launcher position
Target position
Firing angle

In this scenario, the target and the launcher position has the same Y coordinates. I simply instantiate the missile prefab and set its initial rotation to match the firing angle (initial X rotation), rotate it to face the target position (corrected Y rotation), calculate the initial velocity using local space (calculate the Y and Z component of initial velocity), and then set its velocity so the trajectory is handled by the physics engine.

// initial X rotation of the missile: -_firingAngle;
GameObject missile = Instantiate(_projectile, transform.position, Quaternion.Euler(-_firingAngle, 0f, 0f)) as GameObject;
missile.transform.LookAt(_targetPosition);  // fix the Y rotation of the missile
// ...
// velocity calculations
// ...

// launch the missile
missile.GetComponent<Rigidbody>().velocity = Local2GlobalVelocity;

The missile lands its target just fine, however, the X rotation of the projectile during the trajectory doesn't change.

This is how the missile prefab looks like:

I want the missile to be rotated by the physics engine, or put another way, I want it to look natural while in motion. As you may have noticed from the first image, I have visited numerous unity forums to solve the issue. I tried updating the rotation of the missile on each frame as follows

transform.rotation = Quaternion.LookRotation(rb.velocity);

However, this results in a funny trajectory -- imagine an erect missile tilted a little backward, and at the time of landing, the missile is tilted a little forward. I'm not sure why, but when I try to edit the X rotation of the missile mid air when I use the LookRotation(rb.velocity) while the game is paused, the Z value of the rotation also changes. Since the velocity is a Vector3 with non-zero X,Y and Z components, I think the missile is subject to Gimbal Lock.

What are my options to make it look like a trajectory of a badminton ball?

Can I achieve this by adding rigidbodies to the parts that are at the top of the missile and adjust their mass so that the physics engine handles the trajectory rotation as it is a badminton ball, instead of me messing up with the rotation by scripting? If yes, how can I do that exactly?