texts: Why does the object not move correctly when I press the right mouse button?

texts:
2D Game in UNITY C#

I have an object BULLET .

After pressing the left mouse on my object (BULLET), the script allows me to rotate object according to the mouse's direction, in four directions  :

-up right

-down right

-down left

-up left

I would like to add a movement so that the object starts moving in face direction after pressing the right mouse button.

I did it, but the object doesn't move freely in face direction and doesn't bounce off the walls, it just follows the mouse.

But I just want to fire my bullet.

I don't want the object to follow the mouse, just fire in face direction.

You know, like an arrow from a bow.

I press the left mouse button and I start rotate the object - THEN I press the right mouse button and the object flies without stopping in face direction, and began to bounce off the walls.

I show what's wrong on video (link below):
enter link description here

This is my code:

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

    public class TestFollow : MonoBehaviour {

    private Transform _bullet;
    private Vector2 _screenSize;
    private float _interval = 10;
    public Sprite sp1,sp2;
    SpriteRenderer sr;
    bool mouseClicked = false;
    public float moveSpeed = 10f;
    public float speed;
    bool rightClicked = false;

    // Use this for initialization

    void Start ()
    {
        sr = gameObject.GetComponent<SpriteRenderer> ();

        if (sr.sprite == null) // if the sprite on spriteRenderer is null then
            sr.sprite = sp1; // set the sprite to sprite1

        _bullet = transform;
        _screenSize = new Vector2(Screen.width, Screen.height);

    }

    public void Update ()
{

    transform.position = Vector2.Lerp (transform.position, Camera.main.ScreenToWorldPoint (Input.mousePosition), moveSpeed);

    Vector3 difference = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
    difference.Normalize ();

    {
        if (Input.GetMouseButtonDown (0)) {
            Debug.Log ("Left Mouse Button was pressed");
            moveSpeed = 0f;
            if (sr.sprite == sp1) { // if the spriteRenderer sprite = sprite1 then change to sprite2
                sr.sprite = sp2;

            }
            mouseClicked = true; //register that the mouse has been clicked and the sprite is changed to sprite2
        }
    }

    if (mouseClicked) {        //checks if sprite has already been changed

        // Check for every 10 frames, reduce _interval if you want to check more often.
        if (Time.frameCount % _interval == 0) {
            // Use debug to learn mouse position, you can disable this if you want.
            Debug.Log (Input.mousePosition);

            // Mouse on Top Right screen
            _bullet.localEulerAngles = Vector3.zero;

            // Mouse on Bottom Right, else Mouse on Bottom Left else Mouse on Top Left
            if (Input.mousePosition.x > _screenSize.x / 2 && Input.mousePosition.y < _screenSize.y / 2)
                _bullet.Rotate (Vector3.forward, -90, Space.Self);
            else if (Input.mousePosition.x < _screenSize.x / 2 && Input.mousePosition.y < _screenSize.y / 2)
                _bullet.Rotate (Vector3.forward, -180, Space.Self);
            else if (Input.mousePosition.x < _screenSize.x / 2 && Input.mousePosition.y > _screenSize.y / 2)
                _bullet.Rotate (Vector3.forward, 90, Space.Self);
        }
    }

    {

        if (Input.GetMouseButton(1)) {
            Debug.Log ("Pressed secondary button.");
            rightClicked = true;
        }
        if(rightClicked)
            _bullet.transform.position += (transform.right + _bullet.transform.up).normalized * speed * Time.deltaTime;

    }
    }
}

PS. I'm sorry if I shouldn't post here, but I'm in a little depression. I'm working on this code for a few days and I can't change anything.

PS 2. sorry for my English. Not English-speaking country.


texts:
I'm trying to build an '90s style rpg game, think dragon warrior series, where it will have a UI box at the bottom of the screen where the user makes a choice like attack, move, eat etc

I'm thinking of having a game controller (phaser scene?) which updates a board scene and a UI box  scene and displays other scenes if necessary

I am thinking of passing in to the UI box an object with  message, an array of choices and  each choice will have a callback method

So as far as I can tell there are three ways to pass event information to a scene

1) use get scene method to get an instance of a scene and then make calls to that scenes methods

2) using event emitter

3) stopping and starting a scene and passing parameters into the create method

Is one way preferable or another? is there a good coding standard?  Would anyone be able to offer any other helpful hints on how to accomplish the above task


texts: How to set up and use a development environment for games with graphics on a public computer?

texts:
We don't really have any IDEs or development environments with which we could develop games with graphics on school computers. We're on a network run by the school, and can't get technicians to install them, because they're a 'security nightmare' (even though quite a few students can easily circumvent them).

So, what could we do? We'd like to program games in c++ or Java.


texts:
What's the usual way to handle events that are checked both on server and the client, like attacking? There's a cooldown timer to an attack of which the client is aware (so to prevent spamming server requests and attack button is held).

Next there's a cooldown timer on the authoritative server. My problem is that sometimes attacks that end up firing on the client aren't executed on the server, because the server timer (serverFrameTime - lastAttackFrameTime > attackCooldown) didnt count up to the desired time, and so those are 'blank' attacks on the client.

Is there a standard way to handle that without emiting too many messages?
This is a problem for me because i might be firing more of those events and more timers, so autoattacking without clicking is not a long term solution for me.


texts: How do I know the data has arrived at server without requesting every frame of the game?

texts:
I have a game where I have to get data from the server but the problem is I don't know when the data will become available on server. So I decided to use co-routine and hit server at after specific time or on every frame. But certainly this is not the right, scale able and efficient approach.

Now my question is that how do I know that data has arrived at server so that I can use this data to run my game. Or how should I direct the back-end team to design the server in an efficient way that it responds efficiently.

Our back-end team currently uses REST Web services with JSON with Python. And they want to push data to my unity player without my frequent requests.


texts: Translating conditions ("If A has B, then true") into objects that satisfy them ("A has B")

texts:
I have a system where I'm sifting through a large number and variety of objects in my game, looking for objects that match an arbitrary search criteria that can be simple or complex.
For example, suppose a Foo has three integer properties, A, B, and C. I might search the list of Foo objects three times. First, I want to find a Foo where A>5. Second, I might want to find a Foo where A<B or B=8. Third, I might want to find a Foo where A=2, B=6, C>A, and C<B. The point is that I could arbitrarily pass any of a very wide set of conditions into the search.
Now here's my problem. In all cases, if I can't find an item that matches these criteria, I want to create a new Foo that does match, and add it to the list of Foo objects.
The thing I'm wrestling with is figuring out an underlying system of representing conditions that allows me to then create an item that directly matches those conditions. So far I've got two ideas, neither of which I'm a fan of:

Repeatedly generate random Foo objects across the span of possible properties, until applying the criteria to one of them results in true. Given the possible permutations involved, this feels like an absolute performance nightmare, and would probably require a ton of caching logic to track what possibility spaces have already been tried.
Establish a list of individual conditions with isolated variables (such as a GreaterThan condition with the referenced property that indicates whether the property is A, B, or C; and the target value) and create a corresponding declaration (Make [property] a random value between [targetValue] and [propertyMax]). Not only is this incredibly tedious, but I'm also not really confident I understand how it would work, particularly in C# but more generally also. This feels like self-reading code and that's something I have no experience with.

My question is, basically, what designs and techniques can I use to address this sort of issue - the need to create objects that match criteria, when those criteria could be arbitrary? Surely this has come up in other projects. What kinds of constraints or frameworks are applied to make this doable?


texts: Can Mobile Games use Fragments instead of SurfaceViews?

texts:
All the tutorials of mobile games for android (such as this one), use the  to display game objects. Most other applications tend to use an Activity > Layout Resource architecture.

The guide explains why he uses a Activity > SurfaceView Subclass architecture because of threading and canvasing at this point in the video.

Could you use fragments to have take care of threading and displaying game objects?
If you can, why is using a SurfaceView preferred?


texts: Random environment runtime generation in Unity

texts:
I need a tip for a project: basically I need to randomly generate an environment (a map) for a game.
As generating a full map completely procedural is impossible for me, I thought to create a static map (I made one ice based, one rock based, one desert based etc) with some static elements in it like a "spawn area", a map border.

Next, I made some "piece of map" smaller that the actual size of the border (like the border is 1000x1000 and this piece are max 200x200). Each piece has the same style of the border (e.g. I made few icy pieces with a spawn of polar bear and few desert pieces with a spawn of scorpions).

Now I'm stuck; I can't randomly spawn all the little squares inside a border & I can't randomly spawn them inside and make them match one with an other. Incidentally, this is a 3D project.


texts:
Hi I don't speak English very well so ill try to do my best :P

I'm doing my first top-down racing game for LibGDX, now I need to create tracks, the tracks aren't very large, I prefer doing this with a set of tiles with different types of curves, because I want to do a level editor.
So I need to check whether the car is on the track or not. I thought that these alternatives are good but I need help by choosing the best one

An big array. Doing an array of tiles, saving whether in that position there is a track, looks very memory consupting
A set of polygons. And then checking if the car is inside them. Looks very CPU consupting
An Black-White image of the track. I've seen a recomendation here about that, but looks similar to an array

Do you know another way to do this?


texts:
I'm trying to troubleshoot a problem with my simple OpenGL test program, which I've written in C. I've written some math routines to do the matrix manipulation, but even after copying known working perspective functions, I cannot get anything to appear on screen.

The program is simply:

The only geometry is a simple cube centered around the origin, here is the render loop:

int renderer_draw_frame(float delta_time)
{
    glClearColor(0.2f, 0.3f, 0.2f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(prog);

    /* bind textures */
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tile_tex);
    glUniform1i(glGetUniformLocation(spo_prog(spo), "Tex1"), 0);

    vec3f eye = { 0.0f, 0.0f, 3.0f };
    vec3f target = { 0.0f, 0.0f, 0.0f };
    vec3f up = { 0.0f, 1.0f, 0.0f };

    mat4f model_mat = mat4f_translate(0.0f, 0.0f, 0.0f);
    mat4f view_mat = look_at(eye, target, up);
    proj_mat = mat4f_projection(45.0f, (float)win_width / (float)win_height, 0.1f, 100.0f);

    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, &model_mat.f[0]);
    glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &view_mat.f[0]);
    glUniformMatrix4fv(projLoc, 1, GL_FALSE, &proj_mat.f[0]);

    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);
    return 0;
}

mat4f and vec3f is just this:

typedef struct mat4f mat4f;
struct mat4f
{
    float f[4 * 4];
};

typedef struct vec3f vec3f;
struct vec3f
{
    float x;
    float y;
    float z;
};

The math routines in question:

#define M4(m,i,j) m.f[mat4f_idx(i,j)]
#define PI 3.14159265359f

mat4f mat4f_projection(float fov, float ratio, float near, float far)
{
    float d2r = PI / 180.0f;
    float ys = 1.0f / tanf(d2r * fov / 2.0f);
    float xs = ys / ratio;
    float nf = near - far;
    mat4f r = { 0 };
    M4(r, 0, 0) = xs;
    M4(r, 1, 1) = ys;
    M4(r, 2, 2) = (far + near) / nf;
    M4(r, 2, 3) = -1.0f;
    M4(r, 3, 2) = 2 * far * near / nf;
    return r;
}

mat4f look_at(vec3f eye, vec3f center, vec3f up)
{
    vec3f zaxis = vec3f_normalize(vec3f_subv(eye, center));
    vec3f xaxis = vec3f_normalize(vec3f_crossp(vec3f_normalize(up), zaxis));
    vec3f yaxis = vec3f_crossp(zaxis,xaxis);

    mat4f trans = mat4f_id(1.0f, 1.0f, 1.0f, 1.0f);
    M4(trans, 0, 3) = -eye.x;
    M4(trans, 1, 3) = -eye.y;
    M4(trans, 2, 3) = -eye.z;
    mat4f rot = mat4f_id(1.0f, 1.0f, 1.0f, 1.0f);
    M4(rot, 0, 0) = xaxis.x;
    M4(rot, 0, 1) = xaxis.y;
    M4(rot, 0, 2) = xaxis.z;
    M4(rot, 1, 0) = yaxis.x;
    M4(rot, 1, 1) = yaxis.y;
    M4(rot, 1, 2) = yaxis.z;
    M4(rot, 2, 0) = zaxis.x;
    M4(rot, 2, 1) = zaxis.y;
    M4(rot, 2, 2) = zaxis.z;
    return mat4f_mul(rot, trans);
}

Finally, the simple vertex shader:

#version 330 core

layout (location = 0) in vec3 position; //attrib pos 0
layout (location = 1) in vec2 texCoord; //attrib pos 1

out vec2 TexCoord;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    TexCoord = vec2(texCoord.x, 1.0f - texCoord.y);
}

Here is what I see:

If I change the shader as so:

void main()
{
    gl_Position = view * model * vec4(position, 1.0f);
    TexCoord = vec2(texCoord.x, 1.0f - texCoord.y);
}

I see:

Why does it completely disappear in projection view? I've tried changed the view look at parameter but I can't ever see anything through projection view. I've tried several different implementations, currently gluPerspective (the one above is pretty much that function copied).

I've been at this all night and I can't seem to get a grasp on what went wrong. Can someone gives me some pointers on where to go next?


texts: In 2d, how do I discern when a character is on top of an object, from when it is on the side?

texts:
I am building an auto-run platforming game. I have code so that if the character collides with a wall, they are pushed back until they are able to get past the wall. Unfortunately, this means that when the character tries to jump on an object, he just gets pushed backward.

How do I discern when a character is on top of an object, from when it is on the side?

My Current Algorithm (c-ish because i like c-ish syntax):

if(  wall.Top  < (character.Top + character.Height)
 &&  wall.Left < (character.Left + character.Width)
 && (wall.Top  + wall.Height) > character.Top
 && (wall.Left + wall.Width ) > character.Left)
{
  #code here#
}


texts: Accessing other classes from a Box2D (farseer) body

texts:
I'm using Farseer for physics in a game, and have several key classes: Planet and PlanetProp. Each planet has a large circular body and a "field". This field is a large sensor around the body. PlanetProps are pulled towards whichever planet's field they are currently in (a struct called PlanetInfo). So I've set up a collision handler in PlanetProp which will (whenever it is called) detect whether the fixture it has collided with is a sensor.

I then plan to A) detect if the sensor belongs to a Planet and B) Set the PlanetProp to be pulled towards the planet

So in other words, is it possible to access a class using a collision callback with a fixture from a body in that class?

EDIT: Does this involve UserData? If I was using C++ I might be able to put a pointer to the class in that, but I'm using c#.


texts: How can I create a reverb zone depending on audio source location instead of the listener's position?

texts:
Is there a way to make a reverb zone act on an audio source not on the audio listener? Or in other words: Is there a way to apply an audio filter gradually depending on a position in space?

Let's say I have three objects: A plane with a reverb zone attached (some echo-effect), a movable sphere with an audio source and a player character with an audio listener. If I use the player character to push the sphere onto the plane the audio will be echoed, but as soon as the player leaves the plane the audio loses it's effect, because the listener left the zone. Is there any way to make the zone act on the source, not the listener?


texts: How to Continue the state of Unity Game Scene

texts:
I am developing a simple Unity 2D game. During the development of Level One, I wanted the scene to continue after the player is triggered by the enemy and dead util the given 5 lives are completed. When I add Coroutine, it reloads the whole scene and I don't want that...I just want to continue its life from the last hit. So how can I make the scene continue until it loses the whole 5 lives?

void OnTriggerEnter2D (Collider2D col) {
    if (col.gameObject.tag == "Player" ) {
        health.CurrentVal -= 1;
        Explode ();
        if (health.CurrentVal != 0) {
            StartCoroutine ("ReloadGame");
        } else {
            StopAllCoroutines();
        }
    }
}

Thanks!


texts: Curvilinear distortion for mapping texture on quad sphere

texts:
I'm using the formula I've found here to map procedural texture on to a quad sphere.

For example I'm working with a 3d panoramic cube map that I've generated with a simplex noise.

Each face of the cube will be seamless. That's not the point.

My problem is that the corners of each face will have the typical distortion after mapping it onto the quad sphere.

Therefore I want to "manipulate" or prepare the texture ( in this case, the heightmap ) of each face individually with a curvilinear pincushion distortion.

Am I assuming right that the curvilinear pincushion distortion will compensate the distortion effect on the quad sphere ?
Can someone point me to a formula of the curvilinear distortion or the corresponding calculation of the formula I've linked ?

A: original texture. B: what my texture should look like after preparing.

note that B is only a sketch !


texts: How to prevent weapon clipping WITHOUT camera stacking?

texts:
This is a FAQ, and answers involve camera stacking. I am not using a SRP. I do not want camera stacking as various post-processing instructions (e.g. FXAA, MSAA, etc) are all done on the active camera, and redoing all these instructions on multiple camera would be costly

Is there any way to prevent weapon clipping through walls without using camera stacking or a SRP?


texts: I'm trying to set Gizmos.matrix which is a 4x4 by matrix such that the gizmos drawn match the rotation of the object. However, I'm not sure how to convert the transform.rotation quaternion to a Matrix4x4. The Unity documentation points to a function called Matrix4x4.Rotate(), but Unity 5.6 does not seem to recognize any such function under Matrix4x4


texts: Entity's FSM and exposing internals of the entity

texts:
I'm trying to implement FSM according to Programming Game AI by Example, it is a pretty standard and straightforward FSM that goes like similarly to this (some stuff omitted and translated from C++ to C#, hope it's fine):

class StateMachine<Entity>
{
    Entity owner;
    State<Entity> state;

    void StateMachine<Entity>(Entity entity)
    {
        owner = entity;
    }

    void Update()
    {
        state.Execute(owner);
    }
}

class State<Entity>
{
    Entity owner;

    void Execute(Entity owner)
    {
        if (owner.Foo)
            owner.Bar();
    }
}

class Entity()
{
    public type Foo;
    private StateMachine<Entity> stateMachine;

    public void OnStart()
    {
        stateMachine = new StateMachine<Entity>(this);
    }
    public void Bar(){}
}

My problem with this state machine is that the because the state machine is not part of the class anymore (as opposed to, let's say, the naive "switch" / "if-else" implementation), it is necessary to expose internal logic of the Entity (e.g. variable Foo, method Boo()). Is this the right way to do it? What if the the Entity class grows, how does it scale. Is it really necessary to keep exposing more and more variables / creating getters/setters?

How are these FSMs implemented in larger projects?


texts: How do character/object interaction animations work in isometric games?

texts:
I am planning an isometric business simulation game where the player sees an office with the usual furniture such as desks, whiteboards etc.

Characters (Staff/NPC's) within the game should interact with these objects by performing some pre-defined tasks such as typing on the keyboard at the desk or writing on the whiteboard etc.

What I am interested in, specifically, is the following scenario:

Character moves across the office (1) to his desk (2) and sits down and starts to type (3).

From what I understand I would have a sprite sheet for the character movement (1) and a static sprite for the desk (2) but I don't quite understand how the third step would be handled?

Is there a combined sprite that contains both desk and character? I assume not, otherwise I would need to have a sprite sheet for every desk and character combination.

How is this normally handled?

EDIT:

Here is a specific example animation from the game Theme Hospital. You can see the video here.

As far as I can see the animation is split into several steps.

Step 1 - Character moves between desk and chair.

This suggests that chair and desk are in fact separate sprites.

Step 2 - Character sits down animation

Notice how in the very last frame the chair is closer to the desk.

Step 3 - Desk animations

Step 4 - Stand up animation

Is the same as sit down but played in reverse.

Step 5 - Move away

Use normal move animation to move away.

The questions I have is how are these animations best separated and how would a graphic artist usually provide these animations?

Is the character sitting and typing on the desk actually three different sprites (desk, character and chair)? Does anyone know any example sprites of similar animations?

EDIT 2:

I guess my biggest concern is that I have the right expectations on how the sprites will actually look like. I can't draw them myself so I will have to pay someone to do it and I assume there is some kind of best practice way to do these kind of animations?


texts: How to stop a host from the client script?

texts:
I am developing a two player multiplayer game. Since its only two players, I don't want to keep my connection open if a player disconnects.

Now this works well from the host side, through usage of StopHost(). If the player who hosts disconnects, it disconnects both the players from the game.

But using StopHost() in the client(Player B) side does not remove the host player(Player A). In other words, the client is out of the game, but the host is still in the game.

So, what I want is if one player(host or the client whoever it is) disconnects, I want both of them to be disconnected.

So, how can I do it? Please help me with this. I have almost lost hope with UNET. Thanks

EDIT:

My setup is like this, my LobbyManager comprises of UI elements like "TitlePanel", "MainPanel", etc.  The Disconnect button is part of the title panel and gets enabled on press of Esc key. The button is linked to a script attached to the "TitlePanel". This script uses a MonoBehaviour which I changed to NetworkBehaviour in order to use [Command]. But it doesn't work as my "Title Panel" does not have a NetworkIdentity. Adding one creates even more problems

So, I thought if there was a way to send mesages from client to server without NetworkBehaviour, then maybe I could send a flag there to the server.

So is it possible?


texts: GLSL to Cg: why is the effect different?

texts:
With reference to this question, where I was trying to make the shader compile, I am now trying to make an effect appear.
The effect can be shown here, through a GLSL shader:

But when I use the equivalent Cg shader, the result becomes this:

Using the same images (color map + normal map) and the same code (except the way to retrieve variables).

Here is the original GLSL shader;

uniform sampler2D color_texture;
uniform sampler2D normal_texture;

void main() {
    // Extract the normal from the normal map
vec3 normal = normalize(texture2D(normal_texture, gl_TexCoord[0].st).rgb * 2.0 - 1.0);

// Determine where the light is positioned (this can be set however you like)
vec3 light_pos = normalize(vec3(1.0, 1.0, 1.5));

// Calculate the lighting diffuse value
float diffuse = max(dot(normal, light_pos), 0.0);

vec3 color = diffuse * texture2D(color_texture, gl_TexCoord[0].st).rgb;

// Set the output color of our current pixel
gl_FragColor = vec4(color, 1.0);
}

And here is the Cg shader I wrote;

struct fsOutput {
    float4 color : COLOR;
};

uniform sampler2D color_texture : TEXUNIT0;
uniform sampler2D normal_texture : TEXUNIT1;

fsOutput FS_Main(float2 colorCoords : TEXCOORD0,
            float2 normalCoords: TEXCOORD1)
{

    fsOutput fragm;

    float4 anorm = tex2D(normal_texture, normalCoords);
    float3 normal = normalize(anorm.rgb * 2.0f - 1.0f);
    float3 light_pos = normalize(float3(1.0f, 1.0f, 1.5f));
    float diffuse = max(dot(normal, light_pos), 0.0);
    float3 color = diffuse * tex2D(color_texture, colorCoords).rgb;
    fragm.color = float4(color,1.0f);
    return fragm;
}

Please let me know if something needs to be changed in order to obtain the effect, or if you need the C++ code.


texts: How to get a Read-Write Reference to Parent GameObject from a script component attached to it?

texts:
I have a game object(object) with a script component(myscript) attached.

I have a reference to myscript component through getComponent, and I want to change the transform of the gameObject the script is attached to.

myscript.gameObject.transform = (new value);

The above code gives me error,

  Property 'UnityEngine.GameObject.transform' is read only.

Is there a way to get a read-write version?


texts: Where can I find the full game list of Game Design Challenge on GDC?

texts:
The GDC Game Design Challenge is very interesting, the event gives designers the opportunity to display their amazing creativity.

When I searched for the old events I could only find articles which featured one or two games, never the whole list. Is there a record of all the games that have been designed for this event throughout the last ten years?


texts: Modify the Y position of a GameObject on startup

texts:
I'm trying to modify the Y position of a GameObject on startup with the script below:

int y;

void Awake()
{
        y = Random.Range (140, 155);

        Vector3 temp1 = transform.position;

        temp1.y = y;
}

This script does not modify the Y position of the GameObject on startup. What can I do to fix this?


texts: Wikipedia A* pathfinding algorithm takes a lot of time

texts:
I've successfully implemented A* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same.

The map is 80x80, and there are 10-11 nodes.

I took the pseudocode from here Wikipedia

And this is my implementation:

 public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd)
    {
        mMap.ClearNodes();

        mMap.GetTile(mStart.X, mStart.Y).Value = 0;
        mMap.GetTile(mEnd.X, mEnd.Y).Value = 0;

        List<PGNode> openNodes = new List<PGNode>();
        List<PGNode> closedNodes = new List<PGNode>();
        List<PGNode> solutionNodes = new List<PGNode>();

        mStart.G = 0;
        mStart.H = GetManhattanHeuristic(mStart, mEnd);

        solutionNodes.Add(mStart);
        solutionNodes.Add(mEnd);

        openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list.

        while (openNodes.Count > 0) // 2) Repeat the following:
        {
            openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F));

            PGNode current = openNodes[0]; // a) We refer to this as the current square.)

            if (current == mEnd)
            {
                while (current != null)
                {
                    solutionNodes.Add(current);
                    current = current.Parent;
                }

                return solutionNodes;
            }

            openNodes.Remove(current);
            closedNodes.Add(current); // b) Switch it to the closed list.

            List<PGNode> neighborNodes = current.GetNeighborNodes();
            double cost = 0;
            bool isCostBetter = false;

            for (int i = 0; i < neighborNodes.Count; i++)
            {
                PGNode neighbor = neighborNodes[i];
                cost = current.G + 10;
                isCostBetter = false;

                if (neighbor.Passable == false || closedNodes.Contains(neighbor))
                    continue; // If it is not walkable or if it is on the closed list, ignore it.

                if (openNodes.Contains(neighbor) == false)
                {
                    openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list.
                    isCostBetter = true;
                }
                else if (cost < neighbor.G)
                {
                    isCostBetter = true;
                }

                if (isCostBetter)
                {
                    neighbor.Parent = current; //  Make the current square the parent of this square.
                    neighbor.G = cost;
                    neighbor.H = GetManhattanHeuristic(current, neighbor);
                }
            }
        }

        return null;
    }

Here's the heuristic I'm using:

    private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd)
    {
        return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y);
    }

What am I doing wrong? It's an entire day I keep looking at the same code.


texts: how to attach a body to a rope and making it swing to another rope

texts: I've set some ropes (using cocos2d and box2d) and would like to attach a body to one rope in such a way that it can swing to another rope. I am not sure how to go about this. I read  making and object swing from one rope to another but it didn't seem to be of any help.


texts: How can I mod Crusader Kings 2 to prevent vassals from declaring Holy Wars?

texts:
I would like to have a playthrough where my vassals cannot declare wars.

I have set "vassal_wars_law_2" to all my subordinate kingdoms, and yet, this regularly happens:

I think that to prevent this I have to modify something in the

# Regular Holy War CB
religious = {
    name = CB_NAME_RELIGIOUS
    war_name = WAR_NAME_RELIGIOUS

declaration in the 00_cb_types.txt file.

Unfortunately I am quickly out of my depth and I don't know exactly what to change to disable that Casus Belli type for everyone in my empire except me, the emperor.

Can someone please help me in understanding the necessary steps?


texts: How to handle scripted events in a 2d java game?

texts:
I'm in the planning phases of a 2D java game. The game is a tile-based platformer with some action-y parts to it, like a Metroidvania formula game.

The static portion of each stage is expressed as an x y grid of tiles - tile IDs correspond to drawable resources, and a boolean for collision (sky / air space doesn't cause collision with the player, but the ground or an elevated platform would for example)

Additionally, the game uses actors for dynamic things in the game - these could be monsters, boss mobs, moving platforms, checkpoints, powerups - anything that isn't a static tile.

I want to implement a java class ScriptedEvent, and include in each Level a linked list of scriptedevents for the stage.

ScriptedEvent may include a bool hasBeenActivated, bool canBeRepeated (for puzzle-like activities that may be re-ran by the player). I want each instance of ScriptedEvent to do an action, like MovePlayerTo(x,y), or combination of actions - SpawnEnemy(ID,x,y). Scripted events might also change the ID of a ground block to air, allowing the player to fall into a hidden room.

How do you accomplish this task in java? One thought would be to do eval() and have each event contain a string of steps. The steps then could be parsed out one by one from this large string, and interpreted as java code, handled by the main game logic.

Say a very simplfied example constructor might look like:

  ScriptedEvent ev1 = new ScriptedEvent("MovePlayer(200,0); PlaySound('teleport.wav'); SpawnItem(20,205,0);");

Where each function listed in the string would make the game logic do something.

Is there a better way to go about scripted events or should I roll with this solution? I don't really want to hard-code each event into a stage if I can avoid it.


texts: SpriteFont not found in Nuclex Framework

texts:
I am using MonoGame to port my XNA Windows Phone app to iPhone. All is well except that my fonts look distorted/smudged on the iPhone.

Turns out this is due to the way that MonoGame builds the content fonts. They basically let XNA compress them, then MonoGame uncompresses them and re-compresses them again in PVRTC, this causes the distortion. The MonoGame team is aware of that, however no solution out from them yet. Other users have suggested using the Nuclex spritefont processor to bypass compression as shown here, however am unable to do that since I get the following error on build:

Error   1   Building content threw Exception: Font could not be found
   at Nuclex.Fonts.Content.FreeTypeManager.OpenWindowsFont(String searchedFaceName, FontDescriptionStyle style)
   at Nuclex.Fonts.Content.FreeTypeManager.OpenFont(String pathOrFaceName, FontDescriptionStyle style)
   at Nuclex.Fonts.Content.FreeTypeFontProcessor..ctor(FontDescription fontDescription, FontHinter hinter)
   at Nuclex.Fonts.Content.NuclexSpriteFontDescriptionProcessor.Process(FontDescription input, ContentProcessorContext context)
   at Microsoft.Xna.Framework.Content.Pipeline.ContentProcessor`2.Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor.Process(Object input, ContentProcessorContext context)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAssetWorker(BuildItem item)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAsset(BuildItem item)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.RunTheBuild()
   at Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent.RemoteProxy.RunTheBuild(BuildCoordinatorSettings settings, TimestampCache timestampCache, ITaskItem[] sourceAssets, String[]& outputContent, String[]& rebuiltContent, String[]& intermediates, Dictionary`2& dependencyTimestamps, KeyValuePair`2[]& warnings)   c:\users\ramsay\documents\visual studio 2010\Projects\MonogameContent\MonogameContent\MonogameContentContent\BoldFont.spritefont    MonogameContent

The author of the Nuclex framework explains the error

  There's no well-defined API for looking up the font names in Windows,
  so I'm checking the names embedded in the *.ttf files in the Fonts
  directory to find "Courier New" with the appropriate style flags.

So am now I have no idea how to fix this problem and am looking for any advice. It impossible to release an app with all the text looking smudged. However other MonoGame iOS apps are out there with undistorted text, so I am sure there is a solution, but I could not find it anywhere.


texts:
Good Day,
I'm new to Phaser and still learning about it to.
I am challenging my self to create a simple animation of a card flip somewhat realistic
rather that making use of a scale.

This is something that I already started, But having trouble to attain what i need.

See this link http://sopronioli713.github.io/card_masking.

Here is my source code

    <title>Card Masking Flipping Card</title>


texts: Orbits: Combine the Pros of RK4, Symplectic Euler, and Verlet Velocity Integrator

texts:
Recently, I've implemented and compared a number of basic integrators for my physics engine.  The 3 that gave me the best results are RK4, Symplectic Euler, and Verlet Velocity, but I think I need something a little more advanced.  I've done many Google and StackExchange searches but haven't found what I'm looking for.

I'm looking for something that combines the strengths of those integrators without their weaknesses. I'm only concerned about orbital mechanics. Drag and other similar forces will not be put through the integrator because it's not important that I get perfect answers for those other forces, but (near) perfect answers are very important for my orbital mechanics.  Computationally expensive algorithms (within reason) are not as much of a concern as accuracy is.

My thoughts and primary concerns are as follows:

RK4 Pros: Very accurate.
RK4 Cons: Loses energy over the long term.  This sim needs to be able to run for a VERY long time, so experiencing this kind of "orbital decay" is quite undesirable.
Symplectic Euler and Verlet Velocity Pros: Symplectic/Don't lose energy.
Symplectic Euler and Verlet Velocity Cons: Much less accurate.  Highly eccentric orbits make this apparent very quickly...even with a simple massless-satellite-orbiting-a-massive-object scenario, the satellite's orbit "rotates" around the parent object over longer periods of time.  This is extremely undesirable behavior.

For my purposes, I cannot resort to orbits "on rails".

TLDR: I am looking for an algorithm that gives me the accuracy of RK4 without the slow decay.  Computational expense is not a major concern.

Thanks in advance for the help!

Update 1: I found a similar question here: https://stackoverflow.com/questions/3680136/help-with-symplectic-integrators

There might be good answers in the accepted answer, but after several hours of study, I have only determined that they are very difficult to understand.  I will keep studying the accepted answer's linked paper and source code and post an answer if I get results. However, I suspect that while the algorithm is not much more complicated than RK4, the symbology and style of the linked explanations/source code are making it very difficult for anyone without a heavy math/physics background to understand.  Unfortunately, as a comment noted, the OP accepted that answer, but never came back and gave a clearer explanation himself.  I'll leave this question open and keep studying myself. Hopefully, together we can come up with a clearer answer for future searchers!


texts:
I'm developing a game at the moment and I had an idea where the game's story line would randomly generate as the player progressed and their actions would affect the story.

Would this be a bad idea in terms of gameplay or would a storyline that has multiple endings be the best idea?


texts: Learning how to make imposters manually in Unity - how to render an object to a texture not what camera sees?

texts:
I am trying to learn the most performant way to make an imposter in Unity manually - not using pre-fabricated solutions.

My first guess is that it should be achieved by using RenderTexture and a second camera and then taking different "snapshots" of different angles of the objec. If there are better alternatives in terms of performance (even if more difficult to implement), I would love to hear about.

In case that is the only path, then I have learned how to render from a camera to a texture via script, but I still couldn't figure it out how do the following, which is what I need to do first: how to render-to-texture a specific object without the background of the camera (i.e. with rest of texture being transparent) in a performant manner?

Pointers, suggestions or at least link recommendation will be great.

Thanks in advance.


texts: Where/how do I store configuration files in Unity development?

texts:
I am transitioning from working with cocos2d-iphone to Unity.

One particular thing I loved were the .plist files: you could easily put any sort of configuration data you wanted: for game levels, stats, etc.

Now, with Unity, I am not entirely sure if I am supposed to be using such files. I suppose I can, but I'd rather adapt myself to whatever Unity developers use. What is the equivalent to property-list files in Unity development? Plain text files?


texts: Texture with transparency not rendered correctly in LibGDX

texts:
The title might be a bit misleading but I'm having a hard time to explain the problem so I'll try with pictures:

Same tree from opposite site:

I'm trying to create a voxel game and at the moment I try to get textures with transparency working. The mesh is generated for each chunk individually so that every chunk has its own ModelInstance that is rendered.

And the result should be like in the second picture (almost) so that every block is rendered behind the transparent textures but thats not the case for every side.

The relevant code for the transparent textures:

        Mesh mesh = new Mesh(true, meshDataBlended.sizeEstimate, (int)Math.round(meshDataBlended.sizeEstimate * 1.5),
            new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
            new VertexAttribute(VertexAttributes.Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE),
            new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0"));

        BlendingAttribute blendingAttribute = new BlendingAttribute();
        blendingAttribute.blended = false;
        blendingAttribute.sourceFunction = GL20.GL_SRC_ALPHA;
        blendingAttribute.destFunction = GL20.GL_ONE_MINUS_SRC_ALPHA;

        mesh.setVertices(meshDataBlended.vertices);
        mesh.setIndices(meshDataBlended.indices);

        Node terrainNode = modelBuilder.node();
        terrainNode.id = "terrain_blended";

        modelBuilder.part(
                "terrain_blended", mesh, GL20.GL_TRIANGLES,
                new Material(TextureAttribute.createDiffuse(World.TEXTURE), blendingAttribute)
        );

I'm pretty new to OpenGL, so I'm totally lost with this problem. No idea why it behaves like this and I even don't know where I could find the needed informations. So far i just know that it depends on what is rendered first (that's why it works from one side but not the opposite side)
Sorry for using Minecraft textures it's just for testing purposes.

Let me know if some additional information is needed I'll add them then.

Thanks
Blakk

EDIT: setting blended to true will make everything visible behind the leaves except other leaves (still only from specific sides).


texts: Determine corners of a specific plane in the frustum

texts:
I'm working on a game with a 2D view in a 3D world. It's a kind of shoot'em up. I've a spaceship at the center of the screen and i want that ennemies appear at the borders of my window. Now i don't know how to determine positions of the borders of the window.

For example, my camera is at (0,0,0) and looking forward (0,0,1). I set my spaceship at (0,0,50). I also know the near plane (1) and the far plane(1000). I think i'd have to find the 4 corners of the plane in the frustum whose z position is 50, and with these corner i can determine borders. But i don't know how to determine x and y.


texts:
I published an XNA game (for Windows only) using Visual Studio's publish feature which is supposed to handle dependencies and all that.

When I installed it on myself it verified system requirements and installed correctly.

When I tried to install it on a fresh PC, it gave me an error that I was missing the XNA redist. I had to download it separately and then install the game. Is there a way of setting it to download XNA redist automatically as part of the 'one click' installation process? Or will the end user have to stay downloading the redist earlier?


texts: Adapting tilemap algorithm to support isometric tilemap

texts:
I'm using Phaser to build an isometric game. The framework doesn't have support for isometric tilemaps yet, so I'm starting to write a PR for it to support.

What I currently have, loading an isometric tilemap on the current Phaser.Tilemap object, is this:

As you can see, the tiles are wrongly positioned because of the simple 2D tile positioning approach the framework currently uses.

The class that actually makes the parsing of the JSON map and converts it into a tilemap is Phaser.TilemapParser, specifically at line 185.

What I need is some help on where to start adapting this parser – or any other part of the code – in order for it to support isometric tilemaps.

I don't know exactly where to start extending this parser – or even writing a new parser just for isometric tilemaps. Also, I know the calculations are different for positioning isometric tiles, and I want to know too where that change should go here, as I didn't find that either.


texts: Using orientation sensor data for Android game

texts:
I'm building a game where a green box floats to different parts of the screen. The user must rotate their phone such that the blue dot intersects the green square. This is different from a standard "roll-a-ball" type game because instead of tilting a 3D surface the ball sits on, the ball always returns to the center point when the phone is held straight. Tilting the phone forward naturally moves the ball up to catch squares that are above its center position, tilting the phone backward moves the ball down to catch squares below it, and same for tilting the phone left and right. The phone has freedom to pitch, roll, and yaw (XYZ). I'm using the Android SensorEvent and the Sensor.TYPE_ROTATION_VECTOR to try and accomplish this.

So far, this is our approach.

On game start, measure the quaternion returned from the sensor, call it Q1
On all timesteps after game start, compute the transform between Q1 and Qi, Qi being any other quaternion.
Apply the resulting transformation matrix to the 2D dot on the screen such that it translates appropriately.

I'm stuck on computing a transform between Q1 and an arbitrary Qi. I'm asking here to see how similar games solve this problem, and if our approach is even correct given the types of sensor data coming from Android.

Figure1

The bottom two pictures of the phone are side views. The top two pictures are a representation of what's on the screen


texts: Render 3d object to 2d surface (embedded system)

texts:
i am working on an embedded system of a sort, and in some free time i would like to test its drawing capabilities.

System in question is ARM Cortex M3 microcontroller attached to EasyMX Stellaris board. And i have a small 320x240 TFT screen :)

Now, i have some free time each day and i want to create rotating cube.
Micro C PRO for ARM doesnt have 3d drawing capabilities, which means it must be done in software.

From the book Introduction to 3D Game Programming with DirectX 10 i know matrix algebra for transformations but that is cool when you have DirectX to set camera right.

I gues i could make 2d object to rotate, but how would i go with 3d one?

Any ideas and examples are welcome. Although i would prefer advices. I'd like to understand this.


texts: Remove tutorial projects from learn tab in Unity

texts: In Unity I downloaded one of the tutorial projects in the learn tab. However I don't need it anymore. What should I do to get rid of it?


texts: What is the legality regarding allowing players to mod a game with real-life players in a sports game?

texts:
Let's say I'm doing an Indie sports game, and ship it with fictional players, but make the game capable of reading a config file, so that players are able to edit in real names to suit themselves.
The game is a free multi-player, peer-to-peer (p2p) game, and so once the game is published, there is no central server authority which controls what the players are doing, thus allowing them to mod the game as they please.
What's the legal situation with something like that? The file is literally just a plain text file with some names in it. I would imagine that if I were to host that file, and have my game download and consume it on start up, that would be unacceptable, as it would be the same as shipping the game with real player names?
So that makes me wonder, would such a file be illegal for people to share? If I were to make such a file, and distribute it to the community via a forum, would that be illegal? What about if I didn't do that, but a customer did?


texts: How do I size my map in blender so it will be the right size in unity?

texts:
I am working on a fps game but I cant get the size right of my map in blender, every time I export it to a .fbx file (unity won't work if it is a .blend file) it is a super small plane floor in unity the player controller is 10 as big as the map.
I don't know what to do.


texts:
I just learned how to implement a Sound Manager and put sounds into it. The problem is, I'm making a platformer and I have a player, and two different types of enemies who all have footstep sounds. The main issue is that I'm playing all the sounds from the same sound manager and I made the footstep sounds of the player to play like this:
  public void PlayMoveSound()
{
    if(audioSrc.isPlaying == false)
    {
    randomMoveSound = Random.Range(0,5);
    audioSrc.PlayOneShot(moveSounds[randomMoveSound]);
    }
}

I don't know how else to make it NOT sound like its playing 100 times per second so I did this. This gave birth to the issue that the looping audio which is the player's movement sound now blocks me from doing the same thing for the other characters' footstep sounds since it uses the same "audioSrc" AudioSource. Any hints on how different I can create a system for semi-looping audio?


texts: How can I imitate interaction and movement in Diablo II?

texts:
I'm prototyping a simple browser-based game. It's played from a top down perspective on a 2d canvas.

You left-click on a point on the map, and your character will begin walking to it. If you click on a different point on the map, then your character will begin walking to the new point.

It's similar to Diablo II. (a demonstration video)

How can I best imitate this movement system for a player? Ideas...

Track current coords and target coords
If target coords are exactly up, left, right, or down, then increment appropriate direction until you get there
Implied else: target coords are in a quadrant. To make this movement look natural, character will have to move diagonally. For example, pretend the target is to the northeast. For each game frame, alternate incrementing current coordinates in the north and then east directions.


texts: Solve Constraints with linear factor of 0 in Bullet Physics

texts:
In my code I need to set the linear factor for velocity to 0 (sometimes). For example, game->rigidBody->setLinearFactor(btVector3(0, 0, 0)); When this is done, collision detection continues to work, however, collision response fails to work. Essentially running as if there were not colliders at all. I think this is because it applies a velocity to solve the constraints.

Is there an alternative to setLinearFactor or is there another Constraint Solver which does not rely on velocity?

I am using the default btSequentialImpulseConstraintSolver();


texts: Split tile based map file into multiple files

texts:
I have a gigantic map file (1440x1080) that I wish to split into smaller files (45x45) for faster client reading.  I plan to split offline (when running DEV server) so I am not too worried about speed.  Picture the below as my source file:

5, 5, 5, 4, 5, 6, 5... 5
...
5, 6, 2, 44, 5, 66, 5... 5

I am getting the file to be slightly off towards the end - having trouble doing the math I suppose.  I am totally open to changing the code, but here is what I had so far:

int filesAcross = mapWidth / 45;
int acrossCount = 0;
int filesDown = mapHeight / 45;
int downCount = 0;
int totalFileCount = filesAcross * filesDown;

//create a bunch of stringbuilder holders to split the large file into
StringBuilder[] sbGroundLayerHolders = new StringBuilder[totalFileCount];
for (int kk = 0; kk < totalFileCount; kk++) {
    sbGroundLayerHolders[kk] = new StringBuilder();
}

int countt = 0;
while(scanner.hasNext()){
    int fileCounter = (acrossCount / 45) + ((downCount / 45) * filesAcross);
    //  LOGGER.info("fileCounter: " + fileCounter + "   acrossCount: " + acrossCount +
    //"   downCount: " + downCount + "   countt: " + countt);
    try {
        sbGroundLayerHolders[fileCounter].append(scanner.nextShort());
        sbGroundLayerHolders[fileCounter].append(",");
        acrossCount++;

        countt++;
    } catch (InputMismatchException e){
        scanner.nextLine();
        downCount++;
        acrossCount = 0;

        countt++;
    } catch (ArrayIndexOutOfBoundsException e){
        LOGGER.fatal("Array Out of Bounds on ground Layer - count:" + countt, e);
        System.exit(1);
    }
}

//write array contents into files
for (int kk = 0; kk < totalFileCount; kk++) {
    String s = sbGroundLayerHolders[kk].toString();
    s = s.substring(0, s.length() - 1);
    String[] sSplit = s.split(",");

    StringBuilder q = new StringBuilder();
    for (int jj = 0; jj < sSplit.length; jj++) {
        q.append(sSplit[jj]);

        if (((jj+1) % 45) == 0 && jj != 0) {
            q.append(System.lineSeparator());
        } else {
            q.append(",");
        }
    }

    LOGGER.info("map string(" + kk + "): " + q);
    //createFileLocally(folderPath, filename, text);
}

Here is a sample image of what I want to do (smaller scale).  Start with the big grid 6x6 and split into files 2x2.


texts: something very strange in one of the collisions with OpenGL 3.3

texts:
I'm developing a game engine in C, and I came across a problem that left me kind of lost. When I was developing my collision system, I saw something very strange in one of the collisions. During the collision, a white line appeared, well to the legs of the sprite. I have no idea why. I'm using OpenGL 3.3, without additional use of third-party libraries. Before the collision system, I never noticed that, so I think there's something to it. Anyone know what it could be?
NOTE: The sprite that presented the problem was the sprite of the player that moves, in time 1:07. I could not cut the video, because for some reason the video editor sums up with the bug when it rendered the video (maybe because it was small it took as a noise). If you can not see it, reduce the speed to 0.25 on youtube and set to 720p to leave the sharp image!
https://www.youtube.com/watch?v=uC1sQagC_Bw&feature=youtu.be&t=67&fbclid=IwAR2y3w-4w28OwIg27ENZ6vdWvJUpeYgLuGor33uBZ4Z63AYn83QHHKaNeR4
responding to user1118321:

there is the print, it's very subtle, it appears quickly in one of the frames underneath the player. The problem does not seem to be the sprite, because in the surrounding frames, the "white line" does not appear, only at that specific point, and it is a bug that does not always appear, have to try many times to be able to reproduce again


texts: What could cause a sudden stop in Box2D?

texts:
I'm using Box2d for a game, and I have a bug that's driving me nuts. I've simplified the situation down to a square player sliding back and forth frictionlessly on top of a floor composed of a series of square tiles, driven by the left and right keys (which apply a horizontal force). Works great, sliding back and forth across the whole floor.

Except... Every once in a while, the player will suddenly stick at the edge of one of the tiles as if it is hitting a (nonexistent) wall. Further pushes in the same direction it was traveling will fail, but as soon as I push backwards once in the opposite direction, I can push forwards past the sticking point again. The sticking point seems to be random, except for being on the edge of a tile. Happens while going left or right.

For debugging purposes, I keep the Positions/velocity values for the previous two update ticks and print them out when this stop occurs. As an example, here you see the player moving right, decelerating slightly; pos2 should be about 8.7, but it stops dead instead.

tick0:  pos= 8.4636 vel= 7.1875
tick1:  pos= 8.5816 vel= 7.0833
tick2:  pos= 8.5816 vel= 0.0000

So, as the player is 0.8 and the tiles 1.0 wide, the player is stopping just as it is about to cross onto the next tile (8.5816 + 0.8/2 = 8.9816). In fact, I get a collision message (which I ignore except noting that it happened). It only seems to happen at x.5816 (or -x.4184) while moving right, and x.4167 (or -x.5833) while moving left

I said that it's like hitting a wall, but in fact, when it hits a wall, the numbers look more like:

 tick0:  pos0= 12.4131 vel2= 8.4375
 tick1:  pos1= 12.5555 vel1= 8.5417
 tick2:  pos2= 12.5850 vel0= 0.0000

so it moves further right on the last tick, which puts it in contact with the wall.

Anyone seen anything like this. Any suggestion on how I could be causing this behavior.


texts:
I have a question about how scales work in Unity (using 5.0).

I've made a .gif image that is 100x100 pixels in size.

I put it in Resources folder under Assets.

When i drag it onto the scene it looks very tiny.  Scale of it is x:1, y:1, z:1

I've added a 14 size font onto the scene as well for comparison.

You can see the little blue square underneath it.

I don't understand why the square is so small when it came from 100x100 pixel image and the text is only 14 px big.

Am i missing something really simple here?


texts: Trapping mouse inside window in OpenGL with GLUT?

texts:
I perfectly understand that GLUT is limited and the following problem can't probably be solved with OpenGL/GLUT, but since I don't know exactly if it can or not, I better just ask. Maybe I'm doing something wrong or forgetting something important. Or probably not and GLUT doesn't get better than this.

My problem is that I can't trap the mouse inside the window. Well, actually, I can, the code below does just that. I trap the mouse inside the window and I can use the mouse freely to rotate the world. The problem? If I move the mouse too fast I can get way from window prison.

Is there a way around this with OpenGL/GLUT or the only option is another library or make some calls to the Windows API directly? Enough words, here's my current code:

void processPassiveMouseMotion(int x, int y) {
    static int centerX = glutGet(GLUT_WINDOW_WIDTH) / 2;
    static int centerY = glutGet(GLUT_WINDOW_HEIGHT) / 2;

    CameraAngle.x = -1.0f * (y - centerY);
    CameraAngle.y = -1.0f * (x - centerX);

    if(CameraAngle.x != 0.0f || CameraAngle.y != 0.0f) {
        SceneCamera.Rotate(CameraAngle);
        glutPostRedisplay();

        glutWarpPointer(centerX, centerY);
    }
}

glutPassiveMotionFunc(processPassiveMouseMotion);


texts: How to change the position of a circle in pygame in three stages

texts:
I will try to explain it as well as I can excuse me if I'll fail. I have the following simple game situation:

I know the coordinates of each point. So each of the green points try to hit the blue one. I know the target of each green point. What I would like is to acquire a nice movement effect so that lets say each green point will change the coordinates in 3 steps before getting to the target. For example: if a point would be at (2,2) and the target is at (8,9) it would change to (3,3), then (6,7) then (8,9). The idea is how to aceive this? Is there some math involved with sin and cos? I don't know if choosing a random number for example between (2,8) and (2,9) for the new x and y coordinates will do it. I don't know if so it follows the correct direction of the point towards the target.
I use pygame, but if you don't know pygame but can help me with how to aceive this effect is cool. Thanks a lot!


texts: A question. In World Composition there is such a border of the world. As I understand it, everything that goes beyond its limits is destroyed, but is there an option to evade it?


texts: glDeleteBuffers causing other objects not to draw

texts:
I have few objects in scene and they exist until I turn off the application. Their calls for glDeleteBuffers are in destructor. Since I don't delete anything in the middle of the game everything is fine.
But now I created one helper function for drawing lines with following body:

void DrawLine(glm::vec3 p1, glm::vec3 p2, glm::vec4 color)
{
    GLuint vao, vbo;

    glm::vec3 data[2] = { p1, p2 };

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(glm::vec3) * 2, data, GL_STATIC_DRAW);

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glEnableVertexAttribArray(0);

    glBindVertexArray(vao);

    SimpleShader.SetAttribute("World", glm::mat4x4());
    SimpleShader.SetAttribute("UseStaticColor", true);
    SimpleShader.SetAttribute("UseLighting", false);
    SimpleShader.SetAttribute("StaticColor", color);
    glDrawArrays(GL_LINES, 0, 2);
    SimpleShader.SetAttribute("UseStaticColor", false);
    SimpleShader.SetAttribute("UseLighting", true);

    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &vao);
}

But as soon as glDeleteBuffers is called nothing is drawing anymore. If I comment those two lines everything is fine (except a bunch of unreleased object names of course).

Anyone know why is this happening?


texts: First Person Shooter Character in Unity - Meshes Clipping When Close to Body?

texts:
I am working on a game character using Unity. I'd like it to be playable in 3rd Person and 1st Person depending on what the user chooses (switchable in game whenever ideally).

I've worked on and read many examples all using different techiniques (some don't have any mesh for the player and just have a gun; others have no gun at all, just aiming; some use basic geometry only like cylinder and sphere bullet and dont really work when i try using high-poly human like etc).

So I am trying my own ideas and feel like maybe it's impossible for me to make a properly decent game character :[

Here is exactly what I have so far:

a) Mixamo 'Passive_Marker_Man' with idle-rifle-aiming animation.

b) SetIKPosition/Weight for each hand to specific transforms on the gun object.

c) Guns 'butt'/base is the gun objects pivot/origin.

d) The gun is spawned at a transform i made near the models right shoulder

e) Added child object Sphere to player 10 units forward on Z axis

f) Mouse movement on Y moves gun/sphere up and down; mouse X rotates entire player object left/right.

g) SetLookAtPosition IK also done to make head always look at sphere (gun is also always pointed at sphere)

h) camera is set to a position between the two eyes on every frame, and is set to lookAt the sphere.

......When i view this from a 3rd Person perspective it looks pretty good, the guys eyes follow his guns aim, which is pointing nicely at the sphere 10m away.

But if I view it in 1st Person, I can see inside the gun and parts are chopped off etc (aka clipping????)

So am I going about this all the wrong way. It felt so right at some points but now I can't imagine how to stop this kind of thing from ruining the character.


texts: Using Reflection to access an array from a ScriptableObject in Unity

texts:
I am trying to get access to a set of stored variables inside a scriptible object in Unity. This class (SectorDeclaration) has a method to pull a variable with a string of the variables name from it:

public Weightings[] GetVariName(string variableName)
{
    Type this_class = Type.GetType("SectorDeclaration");
    System.Reflection.FieldInfo fieldtype = this_class.GetField(variableName);
    Weightings[] fieldFind = (Weightings[])fieldtype.GetValue(null);
    return (Weightings[])fieldFind;
}

Here's the error I'm getting:

TargetException: Non-static field requires a target
System.Reflection.MonoField.GetValue (System.Object obj) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoField.cs:108)
SectorDeclaration.GetVariName (System.String variableName) (at Assets/Code/Gameplay Element/level Elements/SectorDeclaration.cs:54)
BaseGameManager.InitializeNPCSystem () (at Assets/Code/Managers/BaseGameManager.cs:87)
BaseGameManager.Start () (at Assets/Code/Managers/BaseGameManager.cs:73)

It works until the code reaches Weighting[] fieldFind = (Weighting[])Fieldtype.GetValue(null); I've used this code in another area but it is not working here, I've tried with System.object obj but it comes up with namespace doesn't contain this type, as well as with the type I am trying to access. Honestly, not sure what's wrong. If you need more information please let me know.


texts: Don't Render always on top Unity world space canvas UI

texts: I have a World Space Canvas where I have a text object which is always rendering on top. I checked that it has UI/Default Shader attach. Is there any way available to not render always on top, the 3d UI text.? Any built-in or custom shader available to restrict it? I tried diffuse shader but now the text is not readable. I have also tried a shader from another post at gamedev but the problem is still persist.


texts:
My XNA model renders wrong.

It should render like that:

But it renders like that:

The background doesn't matter. It's just the model that renders wrong.

Here is the drawing code:

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

    DrawModel(model);

    base.Draw(gameTime);
}

private void DrawModel(Model m)
{
    GraphicsDevice.RasterizerState = RasterizerState.CullNone;

    Matrix worldMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(rot))
        * Matrix.CreateTranslation(new Vector3(0,0,0));

    foreach (ModelMesh mesh in m.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = worldMatrix;
            effect.View = viewMatrix;
            effect.Projection = projectionMatrix;
        }

        mesh.Draw();
    }
}


texts: I am having trouble with gravity in my game

texts:
I am trying to detect if the player is on an object with a tag "canHoldWeight". But the detecting if the player is on an object isn't working.

falling code called every tick:

    boolean isObjectSolid;
    boolean isOnObject;
    boolean falling = true;

    for (int i = 0; i < InitObject.getSizeOfAll(); i++)
    {
        GObject object = InitObject.getObjectFromAll(i);

        isOnObject = checkCollision(InitObject.player, object);
        isObjectSolid = object.isHoldWeight();

        if (checkCollision(InitObject.player, object) && isObjectSolid)
        {
            falling = false;
            break;
        }
    }

GObject code (parent of the player and the "ground")

public int rX, rY, hSpeed, vSpeed;
public int x;
public int y;
public boolean dying;
public double dx;
public double dy;
public boolean canHoldWeight;
private Rectangle bounds;
private boolean visible;
private Image image;

public GObject (Image img, int startX, int startY)
{
    image = img;
    visible = true;

    rX = startX;
    rY = startY;

    hSpeed = vSpeed = 0;
    bounds = new Rectangle(startX, startY, img.getWidth(null), img.getHeight(null));
}

public Rectangle getBounds ()
{
    bounds.x = rX;
    bounds.y = rY;
    return bounds;
}

public boolean checkCollision (GObject obj1, GObject obj2)
{
    if (obj1.getBounds().intersects(obj2.getBounds()))
    {
        return true;
    } else
    {
        return false;
    }
}

if you need any more information please let me know :D


texts: Wall collision response results in jittery physics

texts:
I have the following game loop :

while true {
    HandleInput()
    Update()
        PhysicsEngine.HandleCollisions()
        PhysicsEngine.Integrate()
    Render()
}

For now, HandleCollisions is simply negating the velocity vector of the player. The problem is that if I hold the button to walk forward this results in a jittery screen flashing between the render of the forward walk and the backward walk. How can I smooth it out so that it feels like the player has stopped even if I am still pressing the button ?

From what I have found on the internet, Unity's Rigidbody.MovePosition solves this problem, but I was not able to find its implementation online.

One thing that I thought about, but am not sure if it is the solution is the following.

Find distance of penetration in the HandleCollisions function
In the same function move object this much
Change velocity to (0,0,0)

The problem here is that from my understanding the Integration step should be the one doing the movement and I should only be changing velocity. If that is correct, then I have no idea how to solve it.

edit : removed architecture tag


texts: How do you convert angle with velocity to x velocity and y velocity?

texts:
This question can be simplified to:  If you lean a pencil of a certain length at a certain angle what is the x and y position of the tip?
So, basically, I am making a game that plots a balls path through the air as it travels.  I want the user to enter an angle and velocity to launch a ball at and get the program to convert that to an x and y velocity so that it can work out how to plot the balls movement across the screen.  The x velocity doesn't change through the simulation but the y velocity will decrease constantly until the ball touches the ground again.  This is why I referenced to a pencil because it relates to turtle graphics calculations.


texts: Detect clusters of tokens on an x y grid

texts:
Ok, so I have a two dimensional grid working on integer x and y coordinates.

Each of this coordinates can have one and only one token on it.

The tokens have the capability of check and return an adjacent token given a direction in which to search (they'll return null in case nothing is there)

I now need an algorithm to check the grid for clusters of 3 or more adjacent tokens and add each cluster to a dedicated variable (meaning than, instead of just stopping after return one cluster, it needs to check for all clusters on the board)

I've been thinking for a while but came out with nothing, any help?


texts: What software can I use to animate my character in Unity3D?

texts: I am new in game development and I want to know what software can help me to create good animations for my 3rd person character.


texts:
It seems there are three ways to store a camera's rotation: in angles, view matrix or quaternion. I was using euler angles since when I used a matrix it had a tendency to accumulate rounding errors quickly that threw off everything and quaternions would have the same problem.

The problem I've run into is how do I accumulate the rotation? When the camera is rotated, it's rotated in local space about its local XYZ axes. How would you use the given angles in a rotation to rotate about these arbitrary axes? Usually this operation is done with a matrix but it doesn't make sense to try to extract the new angles out of it.

Or perhaps I should be just storing the rotation in a matrix or quaternion? But can this be done without errors eventually causing problems?


texts: Generate platforms and move them with same speed

texts:
I'm building an infinite runner and have to generate pillars on which the player jumps. There's a minimum and maximum value for how much gap can exist between two pillars. In addition to this, i want the pillars to move to the left with increasing velocity. All pillars need to have same velocity.
So, i made a pillarHolder object which would have velocity that increases with time. The instantiated pillars would be made children of this pillarHolder. Code is:

 if ((Vector3.Distance (go.transform.position,transform.position)<25f)) {

                t=rand.Next(13,35);
                t=t/10;
                //Debug.Log(t);
                tempx+=t;

                pos=new Vector2(tempx,-2.22f);

                go=Instantiate(pillar,pos,Quaternion.identity) as GameObject;
                go.GetComponent<Transform>().parent=holder;
            }
holder.GetComponent<Rigidbody2D> ().velocity=new Vector2(-10f,0);

The problem is, the pillarHolder keeps moving in the negative x direction and after a while, the pillars are not positioned properly. The gap between them exceeds the maxGap.
I tried to solve the problem by resetting the pillarHolder's position once it went beyond position.x=-20f. But when it's position resets, child objects are reset too.

Any help please?


texts: What is the difference between "offline" and "real time" rendering?

texts:
I have a rough idea: real-time is approximated with little or no global illumination.
But how would you otherwise explain why offline rending takes so much longer? You hear things like "number of passes," et cetera...

Can you explain the difference in simple terms?


texts:
I'm trying to code a turret to angle towards a target, where I have one part of the turret only rotating on the left/right, and I want to animate another part to only angle up/down. I've got the left/right (RotateTowardsTarget) working, but I can't get the up/down (AngleTowardsTarget) to work, it seems to also rotate the object as well as angle it.

turretXRotation is a child of turretYRotation. These objects form the top of a gun turret, so the base will rotate, and the gun barrel will angle towards the target

/// <summary>
/// Orient the turret weapon towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void OrientWeaponsTowards(Vector3 lookPosition)
{
    RotateTowardsTarget(lookPosition);
    AngleTowardsTarget(lookPosition);
}

/// <summary>
/// Rotate towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void RotateTowardsTarget(Vector3 lookPosition)
{
    // Determine which direction to rotate towards
    Vector3 targetDirection = lookPosition - transform.position;

    // The step size is equal to speed times frame time.
    float singleStep = weaponRotationSpeed * Time.deltaTime;

    // Rotate the forward vector towards the target direction by one step
    Vector3 newDirection = Vector3.RotateTowards(
        turretYRotation.transform.forward,
        targetDirection,
        singleStep,
        0.0f
    );

    // Draw a ray pointing at our target in
    //Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3);

    newDirection.y = 0;
    // Calculate a rotation a step closer to the target and applies rotation to this object
    turretYRotation.transform.rotation = Quaternion.LookRotation(newDirection);
}

/// <summary>
/// Angle towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void AngleTowardsTarget(Vector3 lookPosition)
{
    // Determine which direction to rotate towards
    Vector3 targetDirection = lookPosition - turretXRotation.transform.position;

    // The step size is equal to speed times frame time.
    float singleStep = weaponRotationSpeed * Time.deltaTime;

    // Rotate the forward vector towards the target direction by one step
    Vector3 newDirection = Vector3.RotateTowards(
        turretXRotation.transform.forward,
        targetDirection,
        singleStep,
        0.0f
    );

    // Draw a ray pointing at our target in
    //Debug.DrawRay(turretXRotation.transform.position, newDirection, Color.red, 3);

    // Calculate a rotation a step closer to the target and applies rotation to this object
    turretXRotation.transform.rotation = Quaternion.LookRotation(newDirection);
}

Does anyone know how I can just make the `turretXRotation` only change it's X value to aim towards the target? I've tried similar stuff to the rotating, by zeroing out some of the x/y/z coords, but I can't seem to crack it.


texts: Why does the resolution of floating point numbers decrease further from an origin?

texts:
My OpenGL scene has objects that are positioned at ridiculously far distances away from the origin. When I view these objects, and pan/rotate/zoom a camera around them, they 'jitter'. That is, the vertices comprising the objects seem to snap around an imaginary 3d grid of points. I've read this is a common problem because of the amount of information that can be stored using floating point precision (which OpenGL, and pretty much everything else uses). I don't get why this happens though.

When searching for a solution, I came across the very simple 'floating origin' fix, and it seems to work. I just transform everything so my objects are in the same relative positions but whatever my camera's looking at is close to the origin. I found an explanation here: http://floatingorigin.com/, but I couldn't follow it.

So...Could someone explain why positioning my scene very far away (say 10 million units) from the origin results in the erratic behaviour I observed? And also why moving it close to the origin fixes the problem?


texts: How to account for acceleration when aiming projectiles?

texts: How do I aim a constant speed projectile to hit a target if there is a constant acceleration vector acting on it? (For example, the wind and gravity from Worms.)


texts: How to make character gain acceleration?

texts:
I want to create more realistic physics for my 2D games.

Currently, the character and the other game objects in my games start moving instantly (achieve maximum speed instantly) and stop instantly (achieve 0 speed instantly).

There is no transition between speed levels - resting and moving, moving and resting.

I heard about 'steering behaviors', but am pretty sure they're mostly for designing AI agents' movements.

Should I learn steering behaviors to make more realistic character movements in general? (In the physics-aspect). Is this the way to go?

If the answer is 'yes', could you recommend a good source to learn them?


texts:
When creating the main game loop, what order should things generally happen? IE, should i be getting input, doing logic and then rendering, or something else? does this even matter? when i was coding with python and pygame the tutorial i was using pointed me towards the aforementioned method. however, A tutorial for LWJGL2 (http://thecodinguniverse.com/lwjgl-window/) does it like this:

while (!Display.isCloseRequested()) {
// While no attempt to close the display is made..
// Put render code here.
// Put input handling code here.
Display.update();
// Refresh the display and poll input.
Display.sync(60);
// Wait until 16.67 milliseconds have passed. (Maintain 60 frames-per-second)

and (so far) doesn't seem to have hinted at logic (though i assume it will later on, and looks like it might put it last)

so which should i be using? does it matter at all?
i'm using LWJGL2.


texts:
I am currently trying to make a Mario-type platformer using pygame and the MVC design pattern. My progress as of right now is getting a character on screen and having it move left and right.

My goal is to have this character have the ability to jump when spacebar is pressed. It is definitely recognizing that spacebar is pressed, but the character just stops in place instead of jumping. Here is the code for the character that I currently have:

import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, name, x, y, img_file):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load(img_file).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.falling = True
        self.onGround = False
        self.v = 0
        self.speed = 2

    def moveLeft(self):
        self.rect.x -= self.speed
    def moveRight(self):
        self.rect.x += self.speed
    def jump(self):
        if self.onGround == False:
            return
        self.velocity = 8
        self.onGround = False

and here is the controller part corresponding to this:

if event.type == pygame.KEYDOWN:
    if(event.key == pygame.K_SPACE):
        self.player.jump()

Thanks


texts: 2D game - Missile shooting problem on Android

texts:
I have to make a tank that sits still but moves his turret and shoots missiles.

As this is my first Android application ever and I haven't done any game development either, I've come across a few problems...

Now, I did the tank and the moving turret once I read the Android tutorial for the LunarLander sample code. So this code is based on the LunarLander code.

But I'm having trouble doing the missile firing then SPACE button is being pressed.

private void doDraw(Canvas canvas) {

canvas.drawBitmap(backgroundImage, 0, 0, null);
// draws the tank
canvas.drawBitmap(tank, x_tank, y_tank, new Paint());
// draws and rotates the tank turret
canvas.rotate((float) mHeading, (float) x_turret + mTurretWidth, y_turret);
canvas.drawBitmap(turret, x_turret, y_turret, new Paint());

// draws the grenade that is a regular circle  from ShapeDrawable class
bullet.setBounds(x_bullet, y_bullet, x_bullet + width, y_bullet + height);
bullet.draw(canvas);

}

UPDATE GAME method

private void updateGame() throws
 InterruptedException {

 long now = System.currentTimeMillis();

 if (mLastTime > now)  return; double
 elapsed = (now - mLastTime) / 1000.0;
 mLastTime = now;

 // dUP and dDown, rotates the turret
 from 0 to 75 degrees. if (dUp)
 mHeading += 1 * (PHYS_SLEW_SEC *
 elapsed);

 if (mHeading >= 75) mHeading = 75;

 if (dDown) mHeading += (-1) *
 (PHYS_SLEW_SEC * elapsed); if
 (mHeading < 0) mHeading = 0;

 if (dSpace){

//  missile Logic, a straight trajectorie for now
       x_bullet -= 1;
       y_bullet -= 1;

//doesn't work, has to be updated every pixel or what?

 }

boolean doKeyDown(int keyCode, KeyEvent msg) {
            boolean handled = false;
            synchronized (mSurfaceHolder) {
                if (keyCode == KeyEvent.KEYCODE_SPACE){
                    dSpace = true;
                    handled = true;
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP){
                    dUp = true;
                    handled = true;
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                    dDown = true;
                    handled = true;
                }
                return handled;
            }
        }

}
a method run that runs the game...

public void run() {
            while (mRun) {
                Canvas c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                        if (mMode == STATE_RUNNING)
                         updateGame();
                        doDraw(c);
                    }
                } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        mSurfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }

So the question would be, how do I make that the bullet is fired on a single SPACE key press from the turret to the end of the screen?

Could you help me out here, I seem to be in the dark here...

Thanks,

Niksa


texts:
I have a character and I would like to animate a walking animation for it. However i get the following result when I animate it:

(ignore the green lines/ markers/ sound) As you can see the foot animation is also being applied to the character with predictably bad results. I currently have one animation which applies to the entire character which the foot is a part of. This animation has two layers and can be seen here:

The real problem I am having is how does one get an animation to only apply to a section of the character? I know this can be accomplished with avatar masks but i believe those are only for 3d animations/projects (this is 2d) but if you can get this to work with 2d animations please explain.

The animation that I am using just changes positions, and rotations which is unfortunately applying to the entire object. It also should change the sprite of the feet however this is not taking effect. Ignore the fact that there is only one foot, the other was disabled but exhibits the same behaviour as is seen in the shown foot.

This is a 2d project.


texts: How could you parallelise a 2D boids simulation

texts:
How could you program a 2D boids simulation in such a way that it could use processing power from different sources (clusters, gpu).

In the above example, the non-coloured particles move around until they cluster (yellow) and stop moving.

The problem is that all the entities could potentially interact with each other although an entity in the top left is unlikely to interact with one in the bottom right. If the domain was split into different segments, it may speed the whole thing up, But if an entity wanted to cross into another segment there may be problems.

At the moment this simulation works with 5000 entities with a good frame rate, I would like to try this with millions if possible.

Would it be possible to use quad trees to further optimise this? Any other suggestions?


texts: Can I change shape of a rigid body after it created in Bullet3D?

texts: I'm beginning Bullet3D. Can I change collision shape of a rigid body after it created? A rigid body accepts a collision shape when it's creating, but it's hard to find options changes the collision shape of an instance.


texts:
I've got two points which I need to create a bounding box with, and then check to see if points are within this bounding box. The end result is a marquee selection tool.

So, here is the code I started with:

    var v1 = Camera.main.ScreenToViewportPoint( screenPosition1 );
    var v2 = Camera.main.ScreenToViewportPoint( screenPosition2 );
    var min = Vector3.Min( v1, v2 );
    var max = Vector3.Max( v1, v2 );
    //min.z = camera.nearClipPlane;
    //max.z = camera.farClipPlane;

    var bounds = new Bounds();
    bounds.SetMinMax( min, max );
    return bounds;

So then when I run it, it seems to create the correct bounds:
Center (0.4,0.4,22.3), Extends (0.2,0.2,0.0)

And the point seems like it should be within:
(0.4,0.3,22.4)

Now, my initial thoughts were that the z-index was off. However, i've tried setting that a bunch of different ways, including setting the z index of the center to 22, and the extent to 25. Nothing works.

I'm checking to see if it's contained, with:

bool unitInsideSelection = viewportBounds.Contains(camera.WorldToViewportPoint( gameObject.transform.position ) );

Where viewportBounds is the return object of the function above.

Any Thoughts?


texts: How to prevent (most) cheating (server-side) in my JavaScript, Node JS, socket.io MORPG?

texts:
I'm working on a fairly simple JavaScript + Node JS + socket.io (M)MORPG where multiple people play in the same world.
This is actually working, but cheating is insanely easy at the moment.

My goal is not to stop people from cheating client-side, I know this is impossible.
My goal is to have the server know when someone is cheating and do something about it.
What I really want to know is how well a Node JS server would be able to handle the constant anti-cheat checking.

People can just adjust the client-side JS code and the server currently doesn't do too much checking.

So a player could just change his X & Y coordinate and teleport around the map at will.

It would be fairly simple to implement basic checks that don't allow crazy cheats.
But I'd like a real way to prevent this.

One possibility is to keep track of all player data on the server and make sure nothing weird is happening client-side by constantly comparing the data the server has.
My issue with this is that I have a lot of collision checking and my world will become rather big.
I'm not sure how good of an idea it is to do all of this collision checking server side as well. Sure it would work for one or two players, but what about 10? 50? 200?
Especially with all of these players bouncing off walls, shooting bullets, hitting monsters, getting hit by monsters, colliding with monsters, ...

As far as I know, the only way to actually prevent cheating is by making the server check all movement and wall/bullet/monster collisions.

Are there any other options? Like using an anti-cheat engine of some sort? I know games like MapleStory have that, but I have no idea how they work or how affordable that would be?

Or will doing all the collision checks server side be fine?
At some point, like around 50-100 players, I could set up a second server instance to limit the amount of players on each server.
Ofcourse I would also only check collisions near the player, so not map-wide for each player.

Any help/advice on this is appreciated.

Here's a link to my game that will make my questions less abstract.
It's far from finished and the world is still very small, but it should give a good idea of what I'm asking:

http://185.115.218.199:3000/


texts: How do I make a doorway going into the next scene?

texts:
I new to GDevelop and I use it on a Chromebook.
I'm making this game that I'm kind of proud of! I've found a way to teleport players to the next scene, by just putting the condition, then just make the event: Open url (and then the link of the scene I want the player to travel to). When I use the method I am using now, The game keeps opening tabs of different scenes! And, when I try going back to a tab, It creates like, eight new tabs! It is probably just a glitch. I go to the events section then I set the action to be: open url or file: And then the link of the next scene. I would just like to find a better way.
Can I get a javascript code to make the player teleport when it touches the door or the teleporter?
I would really like to find a BETTER way to teleport the player.


texts: ERROR : Destroying assets is not permitted to avoid data loss

texts:
I want my gameObject named lvl_01 to destroy when I click left or right arrow key but it's keep showing this error "Destroying assets is not permitted to avoid data loss" instead of destroying that gameObject, Can anybody please tell me what is going wrong around here.

using UnityEngine;
using System.Collections;

public class Level_01Text : MonoBehaviour {
public GameObject lvl_01;
// Use this for initialization
void Start () {
    Instantiate (lvl_01);
}

// Update is called once per frame
void Update () {
    if((Input.GetKey(KeyCode.RightArrow)) || (Input.GetKey(KeyCode.LeftArrow)))
    {
        Destroy (lvl_01);
        Debug.Log ("Something is seriously going wrong around here");
    }
}

}


texts:
I'm building Tetris in Java and am trying to use linear algebra to rotate a piece composed of 4 tiles.

My friend was explaining the way to do it is:

He said:

  "To clarify, you do need to rotate each point -- that is you need to
  rotate one point for each Tile in a Piece. But NOT four corners for
  each Tile in a Piece. The origin is like if you stuck a pencil through
  a piece of paper and spun the pencil around.. the spot where the
  pencil is is the origin."

  "So if you have a T on your board with Tiles at (7,9) (8,9) (9,9),
  (8,10) and its origin is at (8,9).."

So I'm doing it with coordinates (1, 3) (1, 2) (1, 1) (2, 2)… with origin (1, 2)

Then he said:

  "You translate the Tiles to be relative to the origin. That is, you
  treat the origin as the new (0, 0) for this rotation. That's as easy
  as just subtracting the origin from each coordinate, giving you (7-8,
  9-9), (8-8, 9-9), (9-8, 9-9), (8-8, 10-9) or (-1, 0) (0, 0) (1, 0) (0,
  1)"

Subtract origin (1, 2) from each coordinate

(1-1, 3-2) (1-1, 2-2) (1-1, 1-2) (2-1, 2-2) =

(0, 1) (0, 0) (0, -1) (1, 0)

Then he said:

  "Now rotate these four coordinates using the rotation matrix
  multiplication, like we have been talking about."

Finally he said:

  "Then add the origin coordinates back to each resulting coordinate,
  and now you have your four rotated Tile coordinates."

From the matrix above, I have (0, -1) (0, 0) (0, 1) (-1, 0)… so I add these to the origin coordinates like he says
(1-1, 3+0) (1+0, 2+0) (1+0, 1+1) (2-1, 2+0) =

Rotated coordinates: (0, 3) (1, 2) (1, 2) (1, 2)

But, looking on my rotated shape... it's completely wrong:

Any thoughts why?

Thanks!


texts:
I'm trying to get Post Processing working in my Unity Project, with URP enabled, but I'm not seeing it work. I've looked at a few tutorials and I've followed them exactly, but I never see any post processing happen.
Here's the inspector window for my Camera:

And here's the inspector window for my Post Processing GameObject:


texts: How do I find realistic 3D paths for stable and unstable flying rockets?

texts:
I am building a 3D application that simulates launching small rockets. I want to draw their trajectories.

I know that rockets have a degree of stability. I want to include this in the simulation, but I don't know what the physics would look like.

How do I go about calculating a rocket's trajectory?


texts: Circle velocities stay the same after elastic 2D collision

texts:
I am following this paper in trying to create elastic 2D collisions among two circles. The problem is that my end velocities are the same as my start velocities. I've looked over my code and don't see anything off.

This is what I am hoping to achieve:

Maybe a second pair of eyes will notice something obviously wrong:

function resolveCircleCollision(playerOne, playerTwo) {
    // http://www.imada.sdu.dk/~rolf/Edu/DM815/E10/2dcollisions.pdf

    var xDiff = playerTwo.objectData.pos.x - playerOne.objectData.pos.x;
    var yDiff = playerTwo.objectData.pos.y - playerOne.objectData.pos.y;
    var normalVector = new Vector(xDiff, yDiff);

    if(normalVector.mag() <= playerOne.objectData.radius + playerTwo.objectData.radius) {
        // Normal/tangent unit vectors
        var normalUnitVector = normalVector.normalized();
        var tangentUnitVector = new Vector(-1 * normalUnitVector.y,     normalUnitVector.x);

        // Resolve velocity vectors into normal/tangential components
        var playerOneNormalComponent = normalUnitVector.dot(playerOne.velocity);
        var playerOneTangentComponent = tangentUnitVector.dot(playerOne.velocity); // Same post collision
        var playerTwoNormalComponent = normalUnitVector.dot(playerTwo.velocity);
        var playerTwoTangentComponent = tangentUnitVector.dot(playerTwo.velocity); // Same post collision

        // Find normal components post collision
        var playerOneNormalComponentPrime = (playerOneNormalComponent * (playerOne.mass - playerTwo.mass) + (2 * playerTwo.mass * playerTwoNormalComponent)) / (playerOne.mass + playerTwo.mass);
        var playerTwoNormalComponentPrime = (playerTwoNormalComponent * (playerTwo.mass - playerOne.mass) + (2 * playerOne.mass * playerOneNormalComponent)) / (playerOne.mass + playerTwo.mass);

        // Convert the components into vectors
        var playerOneNormalVector = normalUnitVector.multiply(playerOneNormalComponentPrime);
        var playerOneTangentVector = tangentUnitVector.multiply(playerOneTangentComponent);
        var playerTwoNormalVector = normalUnitVector.multiply(playerTwoNormalComponentPrime);
        var playerTwoTangentVector = tangentUnitVector.multiply(playerTwoTangentComponent);

       // Add the two components and set them equal to the player velocities
        playerOne.velocity = playerOneNormalVector.add(playerOneTangentVector);
        playerTwo.velocity = playerTwoNormalVector.add(playerTwoTangentVector);
    }
}


texts: How PhysicsBodyLoader.SCALE of overlap2d runtime works?

texts: What is the purpose of that method is and when I have to use it? Really I have no idea. I also found the source code but that didn't help me much.


texts:
I am binding a texture to draw over some geometry (using the ImmediateModeRenderer20) but the alpha channel of the texture turns into colour black when drawn. Why is that happening?

My draw call loop looks sort of like this:

immediateModeRenderer20.begin(renderer.getUiCamera().combined, GL20.GL_TRIANGLE_STRIP);
immediateModeRenderer20.color(new Color(1, 1, 1, 1));
immediateModeRenderer20.texCoord(distance, tc.y);
immediateModeRenderer20.vertex(point.x, point.y, 0f);
immediateModeRenderer20.end();


texts: Single Switch Script vs Multiple Scripts

texts:
Would it be better to have one script that switches or have multiple scripts with each with their own function?

In example, Lets say I am making a powerup script.

Option 1: Create a single powerup script that switches the effects

switch (/*Enum of effects*/)
{
    case Effect.IncreaseHealth:
        health += amount;
}

Option 2: Create multiple scripts that each does its individual function

Class IncreaseHealthPowerup
{
    protected void Start()
    {
        health += amount
    }
}

This is different from the question of Multiple Script versus Single Script as it is already in component form. The question is whether to further segregate down to the types of component.

I would also like to ask the Pros and Cons of each option with regards to potential development issues, or lack of, as well as the overhead caused in either cases.


texts:
This is a general question which aim is to allow me to start digging on the subject by myself.

As I noticed the general opinion is that scene graphs are good for describing the scene in a level editor (or any editor that the game is using), but the game itself should use some sort of optimized data structure internally and the scene graphs should be somehow "translated" to that data structure before use.

What such internal data structures would be? How one would "translate" a scene graph to such structures.

In general - the more detail you can give me then better. Also references/links are more than welcome. :)


texts: Are GPU physics implementations branchless?

texts: I've implemented MPR on the CPU and in pixel shaders (long story!) and there seems to be unavoidable conditional loops both to find the starting portal as well as to find the final solution.  I know that there is middleware that runs physics on the GPU though. Have they found ways to make MPR or GJK more GPU friendly, such as going branchless? Is it proprietary or published knowledge? Thanks!