texts: How to stop Players and Enemies from pushing each other

texts:
I am developing 2D Top-Down RPG game. I have script that makes my enemy follow the player, and when they touch the player, the player will start to lose HP.
Everything works well, but when they touch each other, the enemy starts pushing the player and also I can push the enemy too.
I use a Rigidbody2D and BoxCollider2d for each of them.
Here is my enemy controller code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour
{
    private Animator myAnim;
    private Transform target;
    public Transform homePos;
    private Rigidbody2D myRB;

    [SerializeField]
    private float speed;
    [SerializeField]
    private float maxRange;
    [SerializeField]
    private float minRange;
    // Start is called before the first frame update
    void Start()
    {
        myAnim = GetComponent<Animator>();
        target = FindObjectOfType<PlayerController>().transform;
        myRB = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Vector3.Distance(target.position, transform.position) <= maxRange && Vector3.Distance(target.position, transform.position)>= minRange)
        {
            FollowPlayer();
        }

        else if(Vector3.Distance(target.position, transform.position) >= maxRange)
        {
            GoHome();
        }
    }

    public void FollowPlayer()
    {
        myAnim.SetBool("isMoving", true);
        myAnim.SetFloat("moveX", (target.position.x - transform.position.x));
        myAnim.SetFloat("moveY", (target.position.y - transform.position.y));
        transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
    public void  GoHome()
    {
        myAnim.SetFloat("moveX", (homePos.position.x - transform.position.x));
        myAnim.SetFloat("moveY", (homePos.position.y - transform.position.y));
        transform.position = Vector3.MoveTowards(transform.position, homePos.position, speed * Time.deltaTime);

        if (Vector3.Distance(transform.position, homePos.position) == 0)
        {
            myAnim.SetBool("isMoving", false);
        }
    }
}


texts:
I have been toying with the idea of having a game that is based purely around crafting. That on its own is not much of a big deal. The way the crafting would work is the problem.

The idea I have is that there are a certain set of base materials with which the player can use to craft things. But aside from these set materials, anything goes. The player could combine the materials in any way they saw fit to create whatever they wanted. And then, with the new items the player has created, proceed to make more.

To me, this idea sounds very implausible and not able to be created. Is it actually possible?


texts: List of Lists for sending paths from client to server?

texts:
I have a client server scenario and I'm looking into distributed AI. I want the server to move x amount of ai characters around a map by pathfinding and then send the x amount of paths to the client which will apply each path to its corresponding AI character. This is for research purposes to see if this approach, by sending the new path of each server AI to the client AI for it to follow, is better than constantly sending a positional update across a network everytime a server gameobject moves slightly. I would like this X amount to range anywhere from 10 to 2000, a big ask i know, but i'll go into what I have atm.

Atm I have this working for 2 AI characters and it can be expanded, but with my existing code it would mean an awful lot of copying and pasting! So on the server when the path is created it is sent to a script which can bundle it into an RPC an send it on its way:

public class GrabbingArrayFromUnitScript : NetworkBehaviour {

public List<Vector3> receivedArrays = new List<Vector3>();
public List<Vector3> receivedArrays1 = new List<Vector3>();

    [ClientRpc]
    void RpcPosFromServerToGoTo(Vector3 [] path, String name)
    {

    if (name == "SeekerPrefab")
    {
        receivedArrays.AddRange (path);
        UnityEngine.Debug.Log ("Received");
    }
    if (name == "SeekerPrefab (1)")
    {
        receivedArrays1.AddRange (path);
        UnityEngine.Debug.Log ("Received 1");
    }

    }

public void PrintPath(Vector3 [] path)
{
    if (isServer)
    {
        UnityEngine.Debug.Log("Send Array ...");
        RpcPosFromServerToGoTo (path, transform.name);
        UnityEngine.Debug.Log("Sent!!");

    }
}

}

So as you can see from the above if I wanted to add more AI characters in I would have to add more if statements to the RPC call, and if I wanted 2000 AI in that would be alot of copying. So what could I do here to reduce this code down? Would I use a list of lists? Any help would be greatly appreciated!


texts: How to create reel/slider with mobile controls

texts:
How can I create a reel/slider with mobile game controls so that it looks something like this?

The slider is normally non visible, and can be accessed if I slide my finger from the right side of the screen to the left. The slider allows me to switch my current weapon and use items in my inventory.
This is my current setup in Unity.

I can figure out the inventory portion of the slider, as there are many tutorials out there on an inventory system, and how to make the slider move based on touch, using something similar to a mobile joystick script, but I can't figure out how to make the slider so that it:

Can "jump" from icon to icon (not have the slider be completely fluid/prevent it from stopping in-between item icons)

Detect what item/slot the slider is currently on (in the case of the example, the item that will be used is the icon in the center of the screen.

Make the icons more transparent the further away it is from the icon in use (I'm guessing that I would have to set the alpha channel value in the color settings of the item to a lower value, but I'm not sure how to detect the icon in use and count how many icons away the other icons are from the one in use.


texts:
I was trying out Unity Network LLAPI, I am following the this tutorial. I wrote everything the same, my server starts well and good with no errors.

When my client tries to add host

int hostId = NetworkTransport.AddHost(topology, port);

like this, it crashes with this error

Cannot open socket on ip {*} and port {12000}; check please your network, most probably port has been already occupied
UnityEngine.Networking.NetworkTransport:AddHost(HostTopology, Int32, String)
Client:Connect() (at path/to/game/files/Client.cs:35)
UnityEngine.EventSystems.EventSystem:Update()

Now if I change port on client side it says Wrong IP or Port.

I tried looking but didn't find much. Don't know what is wrong. Also I'm on Linux


texts: Photon disconnected without any error/warning message

texts:
I'm making online game with Photon and Unity. It was working fine, but suddenly players are disconnected without any warning or errors.

It just happens sometimes fast, sometimes slow, but always happened.

Before user disconnected, it seems it's little laggy and soon player disconnected.

So I changed the log level to all, and saw this message was printed right before player disconnected.

  DisconnectByServerLogic current State: Joined

What is meaning of this? I changed Photon App to new one, but didn't worked. I spent hours to figure out why this is happening, but no progress.

There is only one part that disconnects player, it's event function that invokes user pressed exit game, but it never called and there is no more function that disconnects.

If this causes from my code, I can fix it, but there is no code for disconnect and also there is no information why user keep disconnected.

Only information that I found was just above message but I don't know what that means. Is that mean Photon forcely disconnects player?

I'm stuck here in almost day but I couldn't find any problem in my code.

I'm using Free photon plan, and result of analysis:

4 CCU
1 Rooms Max(I don't know what this means)
15,558 Msg/s per Room Max
895.0 MB Bandwidth
0 Rejected Players

If someone who knows this problem, it will be very appreciate it gimme some advice. Thanks.


texts: Can free Unity Store assets be used in non-Unity games?

texts: Does Unity Store allow to use assets listed as free in games built without the use of Unity engine? It's a pretty big place for free assets and I wonder if this isn't against the Unity Store's usage agreement.


texts: Instantiating without the use of Resource Folder in Unity?

texts: I am making a game which has around 25 prefabs. I want to generate these prefabs randomly one after another and also I am destroying the last prefab. One way is to make an array of gameobjects and then reference the prefabs to them. But this way a lot of memory is being used(around 190 MB) because of which my game crashes in android device. Another alternative is using the resources folder but I want to make asset bundle and I will not be able to make assetbundle of my resource folder. So is there any other way to Instantiate prefabs so that memory usage is also less and aset bundling is also possible.


texts: Does Steam notify the user that they need Java for a game when they buy/download/install it?

texts: My mate and I are gonna make a game for Steam and I, as the programmer, want to use Java as that is my current favorite language. So I need to know, does Steam notify the user that they need Java for a game when they buy/download/install it?


texts:
For a gameserver/backend, I have a navmesh for "walkable" areas in form of points/triangles.

Now I want to check every gametick if the client is still in a legit place and if he shots/casts a spell, if his target is in line of sight.

I found several possibilities, but I am not sure what is performance-wise ideal.

To check if the player is still in the allowed area (and not wallhacking) I would check if his position is in one of the triangles with a algorithm using barycentric coordinates like this:
https://github.com/SebLague/Gamedev-Maths/blob/master/PointInTriangle.cs
But this would mean that every gametick I have to check soooo much triangles.

To check if its LoS I could either check if the line from the player to its target crosses one of the "border" lines of the mesh (which have no other triangle next to it). Those border lines could be computed at bake time and are just a static list for each level. But still it would be a lot lines per check.
Second option I found would be to start a Simple Stupid Funnel Algorithm (http://digestingduck.blogspot.com/2010/03/simple-stupid-funnel-algorithm.html) until LoS is broken.

The questions now are:
How does a good gameserver handle this/can it be optimised?
What way to check is the best/fastest?
Is it common to only check if the position is legit every now and then or every gametick?

The Levels are fairly simple (~300 mesh-triangles, ~200 border lines, 10 players, 10 npcs maybe)


texts: 2D character tile based movement problem

texts:
I am making a Super Mario like 2D platformer and I've encountered a problem.
I need to move this sprite :

When a player presses the right key, the sprite moves by 32 px to the right.
The process of moving the sprite is as follows :

The sprite begins in a StandingIdleFirstStep state (Image 1).
Then the sprite enters a transition state (Image 2). The sprite is moved by 16 px to the right. This state is visible for 256 ms.
Finally, the sprite ends the movement in a StandingIdleSecondStep and has moved 32 px from its starting position (Image 3 - first and third step images differ).

During this entire process, the user cannot interact with the sprite. I can feed the process with a approx. 30 ms delta per frame.

Currently I'm thinking about this solution :

User presses move right
Set moving flag to true
Move sprite by x+=16 px.
Update sprite animation
Draw everything

(after 256 ms)

Check if currentAnimationImageIndex % 2 == 1.
If true (odd image, can't stop there), move sprite by another x+=16 px.
Update sprite animation
Draw everything
Set moving flag to false


texts: Where to store contiguous arrays of components?

texts:
I've been working on an entity component system and have the trouble of where to define/put the arrays of each component type. Each component type is user defined so I do not know what or how many arrays to create so I am guessing I need to do something with templates.

This is what I have done so far with example usage. I am rather confused and not sure if what I have done so far is the way to go about this.

template<class T>
class Component
{
public:

    Component() = default;
    virtual ~Component() {};

private:

    friend class Entity;

    uint64 m_entity_id;

    static std::vector<T> COMPONENTS;

};

Example component:

class Velocity : public Component<Velocity>
{
public:

    ~Velocity();

    float get_x() const;

    float get_y() const;

private:

    float x;
    float y;

};

The idea is that this would create a static array for each component type. This feels like a weird way to achieve my goal but I can't think of any other way.

Have I missed an obvious solution to this problem?


texts: How to avoid self-intersection when applying stroke to a curve?

texts:
I have several Spline2D objects in my code, each of which has a Position, Velocity, and Acceleration method that returns a vector of the specified quantity at a particular time. I've been using these vectors in order to construct geometry to create gradient strokes for the curves, but I'm having problems with self-intersections at steep curves. As an example, here's one curve where I'm having this occur:

Wireframe: http://twitpic.com/2zplw1/full
Filled: http://twitpic.com/2zpmnt/full

As you can see, on the second bend, the inner portion intersects itself, which causes that ugly artifact. Is there a good algorithm/method to stroke curves without causing that self-intersection?

EDIT: More extreme examples, plus a mock-up of what I'd like to achieve:

Wireframe: http://twitpic.com/2ztwzi/full
Filled: http://twitpic.com/2ztwkt/full
Ideal Outcome (Mock-Up): http://twitpic.com/2ztxa8/full


texts:
I'm a little confused about the integration between collision and graphics. They both need to share the same position in the world. The most obvious choice is the center of the entity, which is good for bounding volumes and fixed sized sprites. However, for characters with variable height size sprites like this:

http://gamemedia.wcgame.ru/data/2011-07-17/game-sprite-sheet.jpg

This is no longer good. The character won't align to the ground if I'll draw it from the center. I can just make the sprites the same height, but it will be a waste of memory (the largest sprite is 4 times larger then the smallest one). Even then, this is not an option at all with skeletal sprites like this one:

http://user-generated-content.java-gaming.org/img-vault/212a171fc1ebb27ab77608fb9b2dd9bd9205361ce6300b21a7f8d06d025fbbd8.png

It seems that the graphics need to be drawn from the ground for characters, but not for other images such as scenery and obstacles. The only solution I could think of was having another position called draw-position, which is the entity center for images, and is the the bottom of the collision volume for characters. Then when I draw relative to that position, it should work properly.

I haven't found any references for something like that, so I'm kinda insecure about it. Does anyone knows of a better approach for this problem?

Thanks


texts: In Unity, how do I use the extra time in every frame to do some extra processing?

texts:
Let's say, for example, that my target framerate is 60 frames per second.

Now, I know that I have a maximum of 16.6 milliseconds to "do everything" every frame in order to maintain that framerate.

Let's say that I also have a background task that I wish to run. It will return some results. I don't need them urgently; I just wish to run it and have its results when it's done.

Here's my point. I know when I'm done rendering everything; WaitForEndOfFrame() in a coroutine tells me so. Let's say my last frame took only 13 milliseconds to render instead of 16.6, so I know I have 3.6 milliseconds to spare during which I would like to run my task for exactly those 3.6 miliseconds or less, never going over my 16.6 milliseconds maximum total, and then continue with the next frame, on which I will do the same if I get some spare time.

Could I achieve this using Unity's coroutines (or some other way)? If so, how?


texts: How can I implement beam effects like these?

texts:
I am interested in the techniques I could use to create the following effects:

Can I accomplish this with a particle system or a series of texture quads, or what?

You can see this effects in action here in this video.


texts: Sharpdx DirectX11 MapSubresource is failing trying to map a staging texture

texts:
I'm trying to render to a texture and then pull the image data out.  I've created one texture as a render target and another as a staging texture.  After rendering to the render target, I use CopyResource to copy from the render target texture to the staging texture.  So far, so good.  However, when I use DeviceContext.MapSubresource to get the data from the staging texture, I get E_INVALIDARGS exception, and I can't figure out why.

Here is how I create the staging texture:

        textureDesc = new Texture2DDescription()
        {
            ArraySize = 1,
            BindFlags = BindFlags.None,
            CpuAccessFlags = CpuAccessFlags.Read,
            Format = Format.B8G8R8A8_UNorm,
            Height = 256,
            MipLevels = 1,
            SampleDescription = new SampleDescription(1, 0),
            Usage = ResourceUsage.Staging,
            Width = 256
        };
        _renderStaging = new Texture2D(_dev, textureDesc);

Here is how I populate the staging texture and then try to map it:

            DataStream stream;
            _con.CopyResource(_renderTarget, _renderStaging);
            // The following is the line that fails
            box = _con.MapSubresource(_renderStaging, 0, MapMode.Read, MapFlags.None, out stream);

I have the same code working in C++, so I know I have the general idea right.  This is the working C++ code:

textureDesc.Width = 256;
textureDesc.Height = 256;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.MiscFlags = 0;
textureDesc.Usage = D3D11_USAGE_STAGING;
textureDesc.BindFlags = 0;
textureDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
hr = dev->CreateTexture2D(&textureDesc, NULL, &renderStagingTexture);

devcon->CopyResource(renderStagingTexture, renderTargetTextureMap);
D3D11_MAPPED_SUBRESOURCE mappedResource;
devcon->Map(renderStagingTexture, 0, D3D11_MAP_READ, 0, &mappedResource);


texts: Game Over not appearing in third room (GameMaker Studio 2 Trial)

texts:
This is my first StackExchange post, so forgive me if I make a silly mistake.

Getting to the point, I've made a simple Mario-esque platformer where whenever you die, game over text is printed to the middle of wherever you are on the screen. Dying is an Instance Destroy event triggered by various objects, while the Draw GUI event is triggered by a separate object placed in each room.

The third and final "level" room is where text doesn't appear no matter where you die. I've made multiple attempts to fix this, but nothing appears. I believe part of it involves the room's layout; the other levels were simple "go to the right" styled rooms. The third room goes vertically and is much taller.

The issue also likely involves the camera. I'm using viewport[0]. Room properties are as follows:

Room settings - Width: 3000, Height: 3000
Clear Viewport Background: ON
Camera - X Pos: 0, Y Pos: 2250, Width: 1080, Height: 768
Viewport - X Pos: 0, Y Pos: 0, Width: 1080, Height: 768
Following object: obj_playercube (player object) (Hor. border: 400, Vert. border: 400, Hor. speed: 200, Vert. speed: 200)

This is the code for obj_gameover's Draw GUI event:

draw_set_font(fnt_dead);
draw_set_halign(fa_center);
draw_set_valign(fa_middle);
draw_set_color(c_white);

// (x, y) coordinates of the center of the view

var center_x = view_xview[0] + view_wview[0]/2;

var center_y = view_yview[0] + view_hview[0]/2;

if (!instance_exists(obj_playercube))

{

    draw_text(center_x, center_y, "Game Over\n Press Enter to restart from current room.");
    show_debug_message("Game over has printed");

}

I'm sure it's a matter of adding more variables to account for the room's differing properties compared to the others. I'll try to figure it out myself in the meantime.


texts: Optimal way to find point D that lays at the perpendicular line between point A and line BC

texts:
I am trying to write a script in C# to find the position of point D in 2D space in a specific scenario.

I know the (X,Y) position of point A, which never happens to be on the line that contains the line-segment BC. I also know that point D lies on the perpendicular line that passes through A and crosses BC at a point that we can call P. Also, I know the distance that D is from P. Se the image below:

Can anyone shed some line on which is the most optimal way of achieving that?


texts: Improving the look of a character with solid parts inside a translucent jello exterior

texts:
So my problem is a bit hard to explain. I have a character made out of a jello shell, with an internal skeleton. So let me introduce you to ma boi "Chonker McJello"

The problem is, that I want a rich green slightly transparent jello, without loosing too much details and "whiteness" on the internal skeleton. If I turn the transparency or saturation of the jello down, the jello looks ugly, if I put the jello as I want, the Skeleton looses too much details/turns green. I have thought of different approaches, but do not really know how to achieve the effect I want.

Single sided emission:
Is there a way to make the jello glow internally and light the skeleton up? The emission should only come from the backfaces.

Doing something with the render layers, like rendering the skeleton with transparency on top of the jello again, to make it appear "less affected" by it's color

Everything I have in mind sounds easy but is propably pretty complicated and I don't have a lot of experience with shadergraphs and unity's hdrp. If you have any idea how to achieve the desired effect (maybe not in the way I thought) I would really appreciate your help!
Thanks a lot!


texts: How to get status of LEDs on keyboard and blink LED on keyboard from Unity 3D on Android?

texts:
On Android, with Unity how do I get the status of caps lock, scroll lock and num lock LED's and blink these LEDs for caps lock, scroll lock and num lock from Unity 3D?

Blinking the LEDs will of course enable caps, num or scroll lock.


texts: Difference in light between Unity 5.5.2f1 and Unity 2019

texts:
The lighting is different between Unity 5.5.2f1 and Unity 2019. Please see the attached image.
I dislike the way the lighting is done in the 2019 version. Both verions are installed out of the box, without any additions.
What do I need to change / set up inside Unity 2019, in order to have the exact lighting as in 5.5.2f1 version?


texts: Rotating a gameobject in the Inspector doesn't change direction

texts:
When I add a Cube to a scene, the blue axis (=forward) of the cube points into a certain direction.

When I now change the Y rotation of the cube to 90 in the inspector, the blue arrow doesn't rotate.

I would have expected it to rotate with the rotation that I have defined for the cube.

What is happening here?

To explain more in detail why this is bothering / confusing me:

I want to rebuild the RE4 inventory (which is actual 3D). The items in this inventory can be moved within the "grid":

To do that I have created a suitcase and then I added a gun to it:

As one can see, I have assigned the facing direction properly: The blue axis (=forward) points into the direction of the gun.

Now I wanted to rotate the gun in such a way that it is shown like in the original RE4 inventory.

To do that, I apply a rotation of Y = -90.

The gun looks correctly now:

However, the blue axis now faces the wrong direction in my opinion. Why does it not rotate along with the rotation of the gameobject?

This really confuses me because now when I want to move the gun left or right, I have to change its X position value instead of changing the Z position value.

This just seems wrong to me.

Can somebody tell me what I'm missing here?

Thank you.


texts: How do you create dots in a shape of a letter and make them interact-able for a user to connect them?

texts:
I am making a game where the user is given a letter on screen such as the below image

The user then uses the mouse to draw from one point to another until the shape is drawn.

I wanted to know what is the best way for the program to create these points so that they appear on screen for the user to interact with them?

I have a canvas and the mouse is able to draw on the screen the problem is I don't know how to make the points interact-able with the mouse, so that when the mouse draws on or over the dots that it connects them together to form the letter.


texts: Multiplayer networking and understanding snapshots between client and server

texts:
Please note: Although this question involves a link to the Source Engine, its really a generic question about client-server interactions in multi-player games, and I think can be answered by anyone with such experience.

So I just started reading this article on multiplayer networking and only got through the first paragraph before I already had a slew of questions. Most of these questions can all be addressed if I simply could get help understanding the diagram at the top of the page:

Here is my understanding of the first paragraph, regarding snapshots:

A snapshot is something sampled on the server and broadcasted out to all connected clients. Ideally, in a perfect world with zero latency, clients could send updates to the server, and the server could broadcast each and every update back out to all the other clients. However this is not a perfect world, latency does exist and is both chaotic and unpredictable; and so by servers sending these snapshot "heartbeats" out at regular frequencies, all clients can receive updates at the same rate, consistently. Yes? No? Kinda/sorta?

Assuming I'm more or less correct about the underlying purpose of snapshots, then I'm trying to understand what is happening in that diagram above:

The client is currently at Tick=115, but the server is at Tick=130, but why?! Why is the client behind?
Why does the client "buffer snapshots for 100ms"? What's going on there? Is that just the time it takes (roughly) to process a snapshot from the server?
Why is the server simulating the world (and what does that even mean?!) at 33Hz but only sending out snapshots at 20 Hz?

I know these are a lot of tiny/small questions but think they can be addressed with a single answer explaining what is happening in the diagram. Thanks in advance!


texts:
I'm here with another question about direct 3d 11 (sharpdx).
My terrain engine is working good, but theres a problem with texture mip maps or filter which I can't figure out :/
The problem is basic. Near, the textures look OK:

Far away they're kinda ugly?

Loading it:
 internal Texture2D CreateTexture2DFromBitmap(BitmapSource bitmapSource)
       {
            int Byte = bitmapSource.Size.Width * 4;
            using (var buffer = new DataStream(bitmapSource.Size.Height * Byte, true, true))
            {
                bitmapSource.CopyPixels(Byte, buffer);
                var tex = new Texture2D(device, new Texture2DDescription()
                {
                    Width = bitmapSource.Size.Width,
                    Height = bitmapSource.Size.Height,
                    ArraySize = 1,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Usage = ResourceUsage.Default,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb,
                    MipLevels = 1,
                    OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.Shared,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
                },
                new DataRectangle(buffer.DataPointer, Byte));
                return tex;
            }
       }

Rendering it:
 public override void Create(long assetID, Importeur content, DeviceContext context)
        {
            try
            {
                _diffuseTexture = content.LoadTexture(assetID, TextureType.DiffuseMap);
                context.GenerateMips(_diffuseTexture.MapView);
                context.PixelShader.SetShaderResource(0, _diffuseTexture.MapView);
            }

            catch (Exception e)
            {
                throw e;
            }
        }

Filter:
var samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic,
                MaximumLod = float.MaxValue,
                MinimumLod = 0
            };

Finally got it working, the problem was a thread block code line from my engine.

Thanks for helping!


texts: Creating a png sequence in Flash? details?

texts:
I was wondering if someone could please explain the process and rules for turning an animation into a png sequence, in flash CS5.

I know you can go to export movie and chose png sequence but sometimes I only get 1 frame?

I don't know if my character (which was imported from illustrator) should be a graphic or a movie clip symbol and I also have animation within layers in the timeline, I don't know if they all have to be the immediate timeline??

Also my intention for the animation (png sequence) is to make a sprite sheet with texture packer and then to take it into cocos2d, and then use for my iphone game. If there is anything I need to keep in mind when animating for this purpose, please any advice would help.

One last thing does my animation need to be frame by frame (which is what I have been doing) or can I use classic / motion tweens in my animation and still export as a png sequence.

As I'm sure you can tell i'm pretty new to flash and iphone development so any help or advice would be greatly appreciated, sorry for all the questions.


texts: Why don't we use the whole color depth for normal maps?

texts: All normal maps I've seen are pinkish or bluish. It seems like only a small color range is used. Why do game developers give away so much precision?


texts: How do I use a JBox2D ContactListener to check if my character is standing on the ground?

texts:
I want to know when my character is touching a wall or floor. I've had no luck searching for information on this. I saw a few things about ContactListeners and getContactList(), but I don't understand how to use them.

How can I do this?


texts: How to know if mouse coordinates is delta or absolute on Window and Android in Unity?

texts:
I wrote sample application, that allows to "rotate" object by mouse. Rotation occured by rotating of camera object around central object and the code is following:

float mouseX = -Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");

float magnitude = transform.position.magnitude;

Vector3 mouseSwipe = new Vector3(mouseX, mouseY, 0);
Vector3 startPoint = new Vector3((float)camera.pixelWidth / 2, (float)camera.pixelHeight / 2, magnitude - 1);

Vector3 startPointWorld = camera.ScreenToViewportPoint(startPoint);
Vector3 endPointWord = camera.ScreenToViewportPoint(startPoint + mouseSwipe);

Vector3 mouseSwipeWord = endPointWord - startPointWorld;

float dragLat = mouseSwipeWord.y;
float dragLng = mouseSwipeWord.x;

Vector3 oldPosition = transform.position / magnitude;

float lat = Mathf.Asin(oldPosition.y);
float rsmall = Mathf.Acos(oldPosition.y);

float lng = Mathf.Atan2(oldPosition.z / rsmall, oldPosition.x / rsmall);

lat += dragLat * 10 * 2 * Mathf.PI;
if( lat*180/Mathf.PI > 80 )
{
    lat = 80 * Mathf.PI / 180;
}
else if( lat*180/Mathf.PI < -80)
{
    lat = -80 * Mathf.PI / 180;
}

lng += dragLng * 10 * 2 * Mathf.PI * 2;

float y = Mathf.Sin(lat);
rsmall = Mathf.Cos(lat);

float x = rsmall * Mathf.Cos(lng);
float z = rsmall * Mathf.Sin(lng);

Vector3 newPosition = new Vector3(x, y, z);
newPosition *= magnitude;

transform.position = newPosition;

LookAtTarget();

The code assumes that mouse returns delta value on each swipe and this works well on Windows. For example, if I do several separate swipes, I can gradually rotate object for full circle.

Unfortunately, when I run this on Android, it doesn't happen. Each swipe object restarts from some position, depending on swipe point. I.e. on Android, swipes return in absolute value.

Is it possible to know, whether swipes retunrs delta or absolute values and how? Is it possible to claim compatible return units?


texts: How do I translate accelerometer readings into object movement?

texts:
I am using the DeviceMotionEvent web API, which gives me a device's acceleration split up into x-, y- and z-dimensions and a time interval.

Here's my attempt at moving an object on screen based on these accelerations in data (just the x-dimension, for clarity):

velocity.x = data.acceleration.x * data.interval;

var newLeft = $('.object').position().left + (velocity.x);

$('.object').css({ 'left': newLeft });

This sort of works, but after moving, it goes back to where it started from instead of slowing to a stop.

What am I doing wrong? How do I do this right?

Here's an example of some data the API returns:

{ acceleration:
   { x: -0.048474962000711816,
     y: 0.025074772074713834,
     z: -0.0035549827887938587 },
  accelerationIncludingGravity:
   { x: -0.07826046448306878,
     y: 0.34760814211749236,
     z: -9.804854269410603 },
  rotationRate:
   { alpha: -0.15093386712448556,
     beta: 0.051146754356783085,
     gamma: -0.019824252207518427 },
  interval: 0.05000000074505806 }


texts: How to do Chromatic Aberration on a transparent background?

texts:
I have a problem with a chromatic aberration shader effect...

If I produce the effect on a white background I get exactly what I want:

But if I do the same effect on a transparent background I get this:

In my code I use the following shader to produce the chromatic aberration effect:

// Chromatic Aberration

float DisplacementX = 5;
float DisplacementY = 5;

sampler TextureSampler : register(s0);

float4 main(float4 position : SV_POSITION, float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{

// Offset the main texture coordinates.
float2 texCoord2 = float2(texCoord.x + DisplacementX, texCoord.y + DisplacementY);

float2 texCoord3 = float2(texCoord.x - DisplacementX, texCoord.y - DisplacementY);

float4 color1 = tex2D(TextureSampler, texCoord);
float4 color2 = tex2D(TextureSampler, texCoord2);
float4 color3 = tex2D(TextureSampler, texCoord3);

float alpha = color1.a + color2.a + color3.a;

// Look up into the main texture.
return float4 (color1.r, color2.g, color3.b, alpha);

}

technique RGBSplit
{

pass Pass0
{

PixelShader = compile ps_2_0 main();

}
}

This works great when I set the whole screen to a render target and apply the effect but I want to be able to apply this effect only to the foreground so I can choose which sprites it effects and then draw the background behind the transparent space.

My thinking so far is that I could create a white layer of the foreground image and blend it with the chromatic layer to produce the correct effect like this:

return float4(1, 1, 1, alpha); // Produces white version of layer

But I've unsuccessfully managed to blend it and I always end up with the same result as the second image.

I know this is possible because Teleglitch uses the same effect on bullets etc without effecting the background.

Perhaps someone with better blending knowledge than myself can help point me in the right direction?


texts: Would it be possible to edit character models of a PS1 game, to be played on an emulator?

texts:
There are some abandoned PS1 oldies out there that I would love to see revamped with improved assets. I have some skills with some some modelling programs, so I was wondering if it would be possible to rip some models with or without their textures so that I could try to update them, and experience them on an emulator. Is this possible?

Even if the edited copies cannot be reinserted into the game, would it still be possible to rip the models out so that I could edit them?


texts:
Hello I would like to make a curved healthbar (like if it is drawn on a cylinder). See the spatial UI element left to the shoulder of the character on this photo for what I mean.
There is a main outline in white and inside the green healthbar When health decrease only the green bar get shorter.

I can use blender 3d but this is not so immediate...
Any idea?


texts: How can I capture key events on the Mac when using OpenGL?

texts:
I have code that renders a triangle using OpenGL. I would like to control it using the arrow keys on the keyboard.

Anyone know how I would do this on OS X? I think I can create an Objective-C file and import NSEvent, however, I was looking to try this without the need for Objective-C. I would also like to avoid SDL.


texts: Object Transparency Dithering (as shown in Super Mario Odyssey)

texts:
A couple games I've been playing recently all have a similar goal of dithering objects when they approach the near clip plane.  Super Mario Odyssey applies this dithering-near-clip-plane effect, but along with object intersection dithering for objects like Mario.  I have an example of this dithering in Super Mario Odyssey later in this post.

How would one go about creating this effect in their graphics solution of choice?

The gifs might take a little while to get started.  I couldn't get them to each be under 30 mb :(

Example in Super Mario Odyssey

The balloon of the Odyssey doesn't "exit dithering" until the camera is a good distance away from it.  This could mean dithering is calculated based on object distance from camera, instead surface distance.

Flag starts out with a small dither density, and Mario has no dithering applied to him.  Once the flag is fully opaque, Mario becomes dithered, but only in the portions that is covered.  Also note Mario's coat tail has the "transparency dithering" applied to it.  How are the object's shaders structured to allow this compound effect?

Below is a blown up image of Mario being dithered.  Notice how dithering exists in intersection regions, and when behind objects!


texts: What's the fastest way checking if two moving AABBs intersect?

texts:
I have two AABBs that are moving, what's the fastest way to check if they will intersect under a frame?

By moving I mean not just to check with the usual rectangle intersection method, I mean some kind of simple easy swept test that only returns a boolean, no hit time or anything else.

What I think is to simply do it like this:

But that Hexagon is quite complex and I don't know how to calculate an AABB - Polygon intersection, is there maybe an easier way?

Any programming language that you like the most, I can easily port it.

Thanks.


texts: What is a viable way of finding the minimum swaps to sort numbers in pyramid?

texts:
I have made a game that consists of a pyramid of hexagons with numbers from 00 to 99 randomly positioned in groups of 6, 10 or 15 elements. Now, I'm working to create an auto-solver but for the last 2 weeks, I have got nothing really worth produced, and would like your help.
My objective is to determine the minimum swaps need to turn the left pyramid into the right pyramid:

Obviously, there's a catch: every cell can be exchanged only with it's neighbors cells, as below:

I've tried a lot of approaches with binary heap, BST and others, but I can't seems to find a proper answer. What would be the best algorithm choice to determine the minimum swaps needed to sort this hive?

Thanks in advance for any help,

Marcelo


texts:
I'm currently struggling with finding the offset for my original camera translation after I have applied a rotation for it.

transform = Matrix.CreateScale(new Vector3(1, 0.75f, 1))
            * Matrix.CreateTranslation(-playerpos.X+dash, -playerpos.Y, 1);

rotation = Matrix.CreateRotationX(MathHelper.ToRadians(valuex))
            * Matrix.CreateRotationY(MathHelper.ToRadians(valuey));

transform2 = rotation
            * Matrix.CreateScale(new Vector3(1, 0.75f, 0))
            * Matrix.CreateTranslation(-playerpos.X + dash, -playerpos.Y, 0);

My original transform matrix is for the camera that follows the player, I use transform2 for sprites I want to rotate.

spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null,
                   null, null, null, camera.transform);

spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null,
                   null, null, null, camera.transform2);

Edit:

for (int i = 0; i < 3; i++)
{
  spriteBatch.Draw( world.mcircle[i],
                    new Vector2(5320, 1200),
                    null,
                    Color.White,
                    (world.finishtime * 5) / (i + 1),
                    new Vector2(50, 50),
                    3f,
                    SpriteEffects.None,
                    0);
}

So I pass two different transformations based on whether I want stuff to rotate or not.

But I just can't seem to find the correct offset in position for the rotated sprites, they seem to gravitate towards (0, 0)? as the rotational value increases.

I'd be really glad if someone could help me out with this.

Edit: I think I'd only need a proper origin for the sprite position, because currently it goes towards (0, 0) and I'm unsure how to incorporate one in this state.

Edit:

Tried several origin points for transform2, but when I input the object's coordinates as source, it just displaces it by that amount, and when I set the object's position to (0,0) it still has the same effect as if having the original origin point.

transform2 = Matrix.CreateTranslation(0, 0, 0)
             * (rotation * Matrix.CreateScale(new Vector3(1, 0.75f, 0))
             * Matrix.CreateTranslation((-playerpos.X + dash), -playerpos.Y, 0)); //just an example currently


texts: What are heterogeneous coordinate systems and reasons for using them?

texts:
The book I'm following for a computer graphics course only talks about homogeneous  coordinate systems.

But today, our teacher asked:

  What are the reasons for using heterogeneous coordinate systems?

I cannot find anything about this topic.


texts: Mobile (bluetooth) connection to wiimote/controller

texts:
Looking to make a game for cross-platform mobile game.
(Android, iOS, Win8)

Playing with a controller is a pretty important feature.  Bluetooth connecting with a Wiimote works, but there are a few other bluetooth controllers I'd like to support as well.  I can do this on a PC, because the bluetooth serial/connection is solvable.

Ideally, it'd be write-once.

Maybe a plugin for Unity3d?  Maybe some other engine?
I'm willing to use pretty much any engine that lets me write custom shaders.

At this point, trying to find examples of programs that can successfully connect, even to the wiimote, using bluetooth on a non-rooted android device is not going well.


texts: Why the transform never rotate between the range angle of 70 and -70?

texts:
When running the game the rotationRange is always 0.

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

public class Rotateturret : MonoBehaviour
{
    public enum RotateOnAxis { rotateOnX, rotateOnY, rotateOnZ };
    public bool randomRotation = false;
    [Range(0, 360)]
    public int rotationRange = 70;

    private void Start()
    {

    }

    private void Update()
    {
        if (randomRotation == true)
        {
            rotationRange = Random.Range(rotationRange, -rotationRange);
            transform.Rotate(Vector3.right, rotationRange);
        }
    }
}

I want it to rotate on the x axis between 70 and -70


texts:
I added the kinematic equations to my code and now none of it works.   I get the error rigidbody.torque assign attempt for 'Enemy' is not valid. Input torque is { 0.000000, NaN, 0.000000 }.
UnityEngine.Rigidbody:AddTorque(Vector3)
EnemyBehavour:FixedUpdate() (at Assets/_Scripts/Baddies/EnemyBehavour.cs:61)

it should be fine as far as I can tell, please help.

//speed of enemy
public float speed = .5f;
//base distance enemy will attack player
public float range = 3f;
//how far back enemy will stand
public float stopDistance;
//what the enemy will pursue
private GameObject target;
//targetable Enemies
private GameObject[] targetable;
//itself
private Rigidbody self;
//distance to check against
private float saveDistance;
//get the mass for physics stuff
float mass;
//gets drag for physics
float drag;
//gets angular drag for physics
float adrag;
//checks distance
float distance;
//the player
GameObject player;
GameObject[] turrets;
//the base
GameObject playerBase;
EnemyShoot Shoot;

void Start () {
    //get own rigidbody
    self = GetComponent<Rigidbody> ();
    //playerbase should be obviouse
    playerBase = GameObject.FindGameObjectWithTag ("Base");
    target = playerBase;

    Shoot = GetComponentInChildren<EnemyShoot> ();

    mass = self.mass;
    drag = self.drag;
    adrag = self.angularDrag;
}

void FixedUpdate () {
    target = FindFoe ();

    //checks range and
    if (Vector3.Distance (transform.position, target.transform.position) > range || target == playerBase) {
        target = playerBase;
    }
    Vector3 acceleration = AnglularAcceleration ();
    Vector3 torque = new Vector3 (0f, acceleration.y * mass,0f);
    print (torque.ToString ());

    //look at the pursueing target
    self.AddTorque (torque);
    //move towards the pursuing target
    self.AddForce (transform.forward * speed);

}

Vector3 AnglularAcceleration () {
    // the variables to figure out
    Vector3 AnglAcc;
    float radius;
    Vector3 theta;
    float time;

    //get the radius
    radius = Vector3.Distance (transform.position, target.transform.position);
    //get the dot product between the two points
    float dot = Vector3.Dot (new Vector3 (transform.position.x, 0f, transform.position.z),new Vector3 (target.transform.position.x, 0f, target.transform.position.z));
    //get the arccosine of the angle and convert that to radians
    theta = new Vector3 (0,(Mathf.Acos(dot))*180,0);
    print (theta.ToString ());

    //now find the time
    time = (2f * theta.y) / speed;
    AnglAcc = new Vector3(0f,(speed * speed) / (2f * theta.y),0f);

    return AnglAcc;

}

//checks if turrets or player is within range
GameObject FindFoe() {
    distance = range;
    targetable = GameObject.FindGameObjectsWithTag ("ETarget");

    //sets player base as default target

    foreach (GameObject test in targetable) {
        GameObject testing = test.transform.parent.gameObject;
        print (testing.ToString());
        saveDistance = Vector3.Distance (transform.position, testing.transform.position);
        if (saveDistance < distance) {
            distance = saveDistance;
            print (saveDistance.ToString());
            target = testing;
        }

    }
    return target;

}

}


texts: What graph Search algorithm (s) that can simulate the behaviour of a human searching in a forest

texts:
We are building a game , where a group of humans(AI agents) have to wander seperatly throughout the forest looking for a collectable item.
The forest is represented as a 2d graph with the item randomly placed at an (x,y) coordonate.
Having a random search, while the easiest, doesn't guarantee that in a such big map I will reach the item and doesn't take into account that humans have memory and are able to tell, to a certain degree, weather the have traveled that path before.

A more systematic approach such as DFS, while guarantees that eventually the item will be reached, doesn't feel like a human wandering throughout the forest, it lacks the element of randomness and loss.

What I have in mind so far, is to run DFS to randomly selected batch of the forest. So the forest would be subdivided into randomly placed chunks for each human to wander, overlap and revisit is possible, and it would run DFS in that chunk traversing the subgraph eventually if item not found randomly select another chunk.

What do you guys think of the approach? How would you simulate human like search in a graph?


texts: Ray Tracing concers: Efficient Data Structure and Photon Mapping

texts:
I'm trying to build a simple ray tracer for specific target scenes. An example of such scene can be seen below.

I'm concerned as to what accelerating data structure would be most efficient in this case since all objects are touching but on the other hand, the scene is uniform.

The objects in my ray tracer are stored as a collection of triangles, thus I also have access to individual triangles.

Also, when trying to find the bounding box of the scene, how should infinite planes be handled? Should one instead use the viewing frustum to calculate the bounding box?

A few other questions I have are about photon mapping. I've read the original paper by Jensen and many more material. In the compact data structure for the photon they introduce, they store photon power as 4 chars, which from my understanding is 3 chars for color and 1 for flux. But I don't understand how 1 char is enough to store a flux of the order of 1/n, where n is the number of photons (I'm also a bit confused about flux vs power).

The other question about photon mapping is, if it would be more efficient in my case to store photons per object (or even per Object's triangle) instead of using a balanced kd-tree.

Also, same question about bounding box of the scene but for photon mapping. How should one find a bounding box from the pov of the light when infinite planes are involved?

EDIT: I would like to add one more question. I've seen in some source codes, that are using russian roulette, scaling the photon's power by the material's diffusivity and dividing by the average color. Is this correct? I thought that the point of the russian roulette was to not have to do this and end up with photons with varying and small powers.


texts: How to separate production and test assets during development?

texts:
this is like a complement for Assets Management, database or versioning system?.

I am wondering about how to separate development, specially programmers assets from production assets?

For example, if we keep all the assets on the same repository, how do you keep with programmers assets and final game assets? Do you keep a separate directory for each of those, allowing duplicates? Or do you use some fancy scheme for striping out the "development" and "test" assets from final build?


texts: Perspective projection and ultrawide resolution

texts:
The problem I'm going to describe did not occur to me until very recently, when I got a super ultra-wide monitor (32:9 aspect ratio) and tried playing videogames on it.

TL;DR: the scenery is stretched near the left and right edges of the screen due to how projection onto a plane works. Question: why isn't the standard to use "spherical" canvas instead of a plane?

I tried several games and I noticed that the objects displayed far left and far right on my screen are stretched and appear way too closer than they actually are. I could not figure out any general setting (field of view, focal distance...) to mitigate this uniformly, until I realized how projection works.

The way 3D objects are displayed on a 2D canvas is as follows: the camera consists of a point (focal point) and an infinite plane (canvas). To calculate where another point in front of the camera will be displayed, this point is connected to the focal point and the point drawn on the canvas corresponds to the intersection of this line with the canvas.

No wonder the far left and far right parts of the screen are so stretched! The rays from these vertices intersect the canvas at a very small angle.

This problem would be eliminated if we chose the canvas to be a sphere, ideally with the same curvature as the monitor (in case the monitor is flat, the sphere degenerates into a plane and we have the same situation as before). That way, if we choose a correct position for the focal point (depends on our screen setup, curvature, aspect ratio etc.), no stretching should occur, since the focal point is literally "surrounded" by the canvas, instead of the canvas running away from it in all directions.

So my question is, why isn't the standard to implement this "spherical" projection instead of "planar"? Is it because it happens on such a low level of coding that developers don't care, or the code with spherical projection would be a serious bottleneck compared to what is done now? Or the market with super ultra-wide resolution is so niche that they don't care, but we should expect to see it sometime in the future? Or the standards are so baked in that nobody cares about implementing something new, even if it would make more sense?

Sorry in case this question doesn't quite fit in here, I actually don't know anything about making videogames, but this strikes me as it's more about geometry than actual game-making.


texts: How to get the actor to follow the mouse while clicking and holding?

texts:
I am trying to do the top down project from scratch.

I can already get the actor to move toward the mouse click:

Only I need to keep clicking several times to change its path and keep walking indefinitely.

I would like to know how to keep it moving while I hold the mouse button.

In the previous version (4.21) this code below fit perfectly, so I managed to do that (the condition was a variable that only became false when I released the mouse button):

But now I can't make this connection (4.22).

I searched for some functions and even searched the new documentation for this loop (While Loop), but nothing worked.

Link (While Loop BP UE4):

https://docs.unrealengine.com/en-US/Engine/Blueprints/UserGuide/FlowControl/index.html#whileloop

Player Blueprint:

As I could do this before, you can see in the answer to this question:

How to make my character walk by clicking and holding the mouse button?


texts: How stencil buffer and glFrontFace help making a shadow?

texts:
I'm trying to understand the tutorial 27th in Nehe website. This is about how to cast a shadow of an object using stencil buffer in OpenGL.
The idea here is checking the directions of all the faces of the object with the direction of light, and the result will define whether or not this face make a shadow.
In the case of making a shadow, we will draw "shadow" into the stencil buffer as the following code.

// First Pass. Increase Stencil Value In The Shadow
glFrontFace( GL_CCW );
glStencilOp( GL_KEEP, GL_KEEP, GL_INCR );
doShadowPass( object, lightPosition );
// Second Pass. Decrease Stencil Value In The Shadow
glFrontFace( GL_CW );
glStencilOp( GL_KEEP, GL_KEEP, GL_DECR );
doShadowPass( object, lightPosition );

My question here is why "glFrontFace" function in the second pass help remove shadow between objects in the scene?

I Hope to see your answer. Thanks so much!

P/S:this is the explanation in the tutorial, but I don't get it

"They are rendered in two passes as you can see, one incrementing the stencil buffer with the front faces (casting the shadow), the second decrementing the stencil buffer with the backfaces ("turning off" the shadow between the object and any other surfaces)."


texts: Vulkan am I creating too many graphics pipelines?

texts:
I have the situation in which I require different VkPrimitiveTopology's for different models, which requires me to have a unique pipeline's that render the different models, but now I require multiple windows open at the same time. Is there any way to use the pipelines for multiple windows or will I require a different set for the new window?

The secondary windows could be a different size to the main window, that's why I ask because I know when a window resizes you require to rebuild the pipeline.


texts:
I want to add two types of characters multiple times but when I add a new actor to stage texture in "old" actors stops render.

I can add multiple KnightActor (without RatActor) or multiple RatActor (without KnightActor). When I try to add multiple KnightActor and RatActor on one stage only textures from newest actors are rendered (one RatActor and one KnightActor)

GameScreen.kt

override fun render(delta: Float) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

    actorManager.addNewActors(stage)

    viewPort.camera.update()

    stage.act(delta)
    stage.draw()

    world.step(delta, 8, 3)
    debugger.render(world, viewPort.camera.combined)
}

ActorManager.kt

fun markToAdd(actor: BaseActor<*>) {
    toAdd.add(actor)
}

fun addNewActors(stage: Stage) {
    toAdd.forEach { actor: BaseActor<*> ->
        stage.addActor(actor)
        actor.addToWorld(worldService.getWorld())
        Gdx.app.log("afterAdd", (++charactersOnStage).toString())
    }
    toAdd.clear()
}

KnightActor.kt

override fun draw(batch: Batch, parentAlpha: Float) {
    super.draw(batch, parentAlpha)

    if (isMoving) {
        frameStateTime += Gdx.graphics.deltaTime
    }

    // DRAW TEXTURE
    val frame = animationManager.getFrameAndChangeSpeed(AnimationType.KNIGHT_WALK_RIGHT, frameStateTime, getSpeed())
    val frameX: Float = position.x - (size.width / 2)
    val frameY: Float = position.y - (size.height / 2)

    batch.draw(frame, frameX, frameY, size.width, size.height)

    // END DRAW
}

RatActor.kt

override fun draw(batch: Batch, parentAlpha: Float) {
    super.draw(batch, parentAlpha)

    if (isMoving) {
        frameStateTime += Gdx.graphics.deltaTime
    }

    // DRAW TEXTURE
    val frame = animationManager.getFrameAndChangeSpeed(AnimationType.RAT_WALK_LEFT, frameStateTime, getSpeed())
    val frameX: Float = position.x - (size.width / 2)
    val frameY: Float = position.y - (size.height / 2)

    batch.draw(frame, frameX, frameY, size.width, size.height)

    // END DRAW
}

AnimationManager.kt

fun getAnimation(animationType: AnimationType): Animation<TextureRegion> {
    return AssetsManager.loadSprite(animationType.spriteFile, animationType.alias).getAnimationForSprite(animationType.alias, animationType.width, animationType.height)
}
fun getFrameAndChangeSpeed(animationType: AnimationType, stateTime: Float, speed: Float, looping: Boolean = true): TextureRegion {
    val animation = getAnimation(animationType)
    animation.frameDuration = 1 / speed
    return animation.getKeyFrame(stateTime, looping)
}


texts: Sprite animation in openGL - Some frames are being skipped

texts:
Earlier, I was facing problems on implementing sprite animation in openGL ES.

Now its being sorted up. But the problem that i am facing now is that some of my frames are being skipped when a bullet(a circle) strikes on it.

What I need : A sprite animation should stop at the last frame without skipping any frame.

What I did : Collision Detection function and working properly.

PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case.

------------------------ EDIT-----------------------

My sprite sheet. Consider the animation from Left to right and then from top to bottom

Here is an image for a better understanding.

My spritesheet ...

class FragileSquare{

FloatBuffer fVertexBuffer, mTextureBuffer;
ByteBuffer mColorBuff;
ByteBuffer mIndexBuff;
int[] textures = new int[1];
public boolean beingHitFromBall = false;
int numberSprites = 20;
int columnInt = 4;      //number of columns as int
float columnFloat = 4.0f; //number of columns as float
float rowFloat = 5.0f;
int oldIdx;

public FragileSquare() {
    // TODO Auto-generated constructor stub

    float vertices [] = {-1.0f,1.0f,            //byte index 0
                         1.0f, 1.0f,            //byte index 1
                                    //byte index 2
                         -1.0f, -1.0f,
                         1.0f,-1.0f};           //byte index 3

    float textureCoord[] = {
                            0.0f,0.0f,
                            0.25f,0.0f,
                            0.0f,0.20f,
                            0.25f,0.20f

    };

    byte indices[] = {0, 1, 2,
            1, 2, 3 };

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float
    byteBuffer.order(ByteOrder.nativeOrder());
    fVertexBuffer = byteBuffer.asFloatBuffer();
    fVertexBuffer.put(vertices);
    fVertexBuffer.position(0);

    ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4);
    byteBuffer2.order(ByteOrder.nativeOrder());
    mTextureBuffer =  byteBuffer2.asFloatBuffer();
    mTextureBuffer.put(textureCoord);
    mTextureBuffer.position(0);

}

public void draw(GL10 gl){

    gl.glFrontFace(GL11.GL_CW);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer);

    gl.glEnable(GL10.GL_TEXTURE_2D);
       if(MyRender.flag2==1){ /** Collision has taken place*/
    int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)((System.currentTimeMillis()%(200*numberSprites))/200);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    oldIdx = idx;
    }

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4
    gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7

    gl.glFrontFace(GL11.GL_CCW);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glMatrixMode(GL10.GL_MODELVIEW);

}

public void loadFragileTexture(GL10 gl, Context context, int resource)
{
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
    gl.glGenTextures(1, textures, 0);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();
}


texts: Depth of Field Blur - Weighted sampling?

texts:
I've been studying Intel's fantastic article titled "An investigation of fast real-time GPU-based image blur algorithms" (here), where-in they state that Gaussian blur would need to be customized for proper use in achieving a depth-of-field effect. The relevant part states:

  They are all generic algorithms that are fully applicable to effects
  like a Bloom HDR filter. However, in a specific scenario, for example
  for use in Depth of Field, they would require additional customization
  (such as weighted sampling to avoid haloing/bleeding) which can impact
  relative performance.

However they don't go into detail about how to compute the weighted sampling? Does anyone know what this means, or know of relevant documentation / example code?

I have been using guassian blur for DoF and have indeed seen the bleeding and other artifacts, so I've been looking for ways to solve these problems.


texts: Convert Minimap render texture to 3d space position

texts:
I am using Render Texture to make a Mini Map it is working fine. Now I want world space position from render texture click point.
Is there any way available that I get the world space position from the render texture's specific click point?
If I click somewhere in render texture then, how can I get that point in 3D world space?
For example, I click a car object on render texture How can I highlight or get it in 3D world space.?
Update: Actual Scenario is:

One Main Camera Rendering the Scene.
NGUI Camera Rendering the GUI.
That GUI contains the Render Texture(minimap) which rendering the
scene on texture using GUI Camera.

Now how can I get 3D position from 2D render texture!


texts: Blueprint script executed on tick but not on construction

texts:
Below, on event tick, I am initializing a map of images once, which works fine (remember we are in a graph for a widget blueprint here).

Z Cursor Images is the map of the images. The keys in the map are an enum, and I am adding first an image for the default cursor, and then an image for when the player is targeting an object that she can pick up.
Now, when I do the same in the construction script (Event Construct), it does not throw an error but later I cannot access the textures from the map. IsValid returns false for them...
So why is the map filled on tick but not on Event Construct? And how do I solve this?


texts: How do I handle objects with a width and height in grid-based pathfinding?

texts:
I'm using the Jumper library for Love2D to do grid-based pathfinding, which worked fine until I wanted to make larger enemies (with larger collision boxes). How do i do that?

My initial idea was to make a new map for each entity that needed pathfinding I could make a new map, with all the objects scaled up in size, but that seems way to complicated.

To give an example, I could have a wall with a passageway that is wide enough that my player has no trouble walking around it, but a giant ogre would have to walk around.


texts: Why aren't there game and physics engines with double precision?

texts:
Choice of game design and other human psychological factors aside

is the present hardware not capable of working with double precision floating point calculations with reasonable performance? It can ease all the complicated tricks involved to get large worlds working seamlessly in current single precision float setup.

Correct me if I'm wrong but shouldn't modern x64 processors more suited to this kind of task?

For the problem with gpu performance it should still be easier to work in double precision and translate co-ordinates to float on camera space


texts:
I am currently attempting to convert my screen coordinates to world coordinates, to be able to interact with objects. I am using glm and unProject to try and achieve this, so far this is my code:

glm::vec4 viewPort = glm::vec4(0.0f, 0.0f, width, height);
glm::mat4 tmpView = sceneCamera->updateView();
glm::mat4 tmpProj = sceneCamera->updateProjection();
glm::vec3 screenPos = glm::vec3(touchPosition.x, height - touchPosition.y - 1.0f, 1.0f);
glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);

Renderer->SceneObjects[120]->translateX(worldPos.x);
Renderer->SceneObjects[120]->translateY(worldPos.y);

I am trying to get a sprite to equal the position where I tap.
The issues is that the further I click going down the screen, the further the sprite overshoots, and the same horizontally. So if I click 2/3 the way down the screen, the sprite will overshoot the bottom of the screen.


texts: Moving and rotating object with another object

texts:
Sorry i bad painter))

Need move and rotate 'OBJECT №2' with 'OBJECT №1'

I have origin point(also rotation point) and angles of two object. (Also min and max coordinates of these objects)

Vector origin, Vector angles, Vector absmin and Vector absmax.

I tried next simple code, and it works nice, if object angles not changed:

object2.origin += object1.origin - object1.oldorigin;

(without rotation)

But i need also rotation, I was rarely attend geometry at school, and can't do it without help )))


texts: I think in game design it is incredibly important to ask the question why about everything, especially something that has become so standard as lives. So I am asking, what is the purpose of a game having the concept of lives? Why have lives?


texts: how to make different sprite when moving and aiming

texts:
I want to create top down game where you are Russian soldier in libGDX.
The player controls the soldier with W/A/S/D and aims with the mouse. That way the soldier can run sideways and shoot towards enemy.

What is best way to make his legs walk into the right direction but aim the weapon towards the mouse pointer?

My idea is to make two sprites, for both torso/weapon and legs and let them lay over each other but I don't know if that is best way to do it.


texts: Unity not scrolling when mouse not over object

texts:
In Unity I am using a scroll view. It works semi-perfectly (had a lot of problems with it, don't like how the UI system works).

The content for my scroll view is a bunch of buttons aligned vertically with some spacing between them. The problem is that the scroll rect will only scroll if I'm hovering over one of the buttons. If the mouse is between two buttons, it won't scroll.

Here are some screenshots:

Also, you may see that I'm not using the standard Scroll Rect, mine is nothing special, just disabled the dragging that is stupid to be used on non-touch devices.


texts: How can I make "small" (file size) background music loops/tracks?

texts:
I recently purchased some short (approx 3 min) background music tracks.  I have the tracks in three formats: AIFF, MP3 and WAV.  How can I compress these files such that the quality remains intact (for the most part) and the file size is relatively small?

I'm especially interested in the "before" and "after" file formats.  So far I've tried compressing the MP3 format to m4a.  This reduced the file size substantially... however the quality was significantly degraded.

I'm definitely open to reducing the tracks to much shorter (approx 20 sec) loops.  Also note these background music tracks will be used on the iPhone (need to support back to the 3G).  I have access to Logic Express 9 and Garage Band... and I'm open to trying Audacity or other software.

Cheers!

Edit:  I'd like the file size to be around 300 Kb.  This way it loads quickly on the 3G.


texts: How to make a procedural tilemap island with more than one tile in unity?

texts:
I have been working on a simple survival game. I made the character and some basic elements (I'm new to the field though).
But what I could figure out how to make is the world generation.
I just wanted to make a program that generates an island procedurally. I tried Perlin Noise before, but it wasn't that efficient. The results were too random.

In the past few days, I found a unity package that generates tilemap islands, and I really liked the results, but I didn't know how to make more tiles than just grass.

The problem is that I don't know how can I make a script like this because I am still new to unity. That's why I tried asking for some help.

I just want something that looks like this :

I would really appreciate any help!


texts:
I'm newbie in Unreal development and I don't know how to move my pawn faster.

By the way, I'm using Unreal 4.16.

I'm developing Pong game and I have this method to move the pawn:

void AAIPaddle::MovePaddle(float Scale)
{
    // Add a movement input, hardcoding Z speed to 100.0f
    FVector direction = FVector(0.0f, 0.0f, 100.0f);

    // Scale could be -1.0f or 1.0f or 0.0f.
    AddMovementInput(direction, Scale);
    if (OurMovementComponent &&
        (OurMovementComponent->UpdatedComponent == RootComponent))
    {
        OurMovementComponent->AddInputVector(direction * Scale);
        ZVelocity = Scale;
    }
}

You can find the class AAIPaddle here.

I use this FVector direction = FVector(0.0f, 0.0f, 100.0f); to set its speed, but I change the value 100.0f with 400.0f or another greater values and it moves with the same speed.

Maybe I haven't understood anything. How can I change its movement speed?

I'm using the following class that inherits from UPawnMovementComponent.

void UPaddlePawnMovementComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    // Make sure that everything is still valid, and that we are allowed to move.
    //      PawnOwner: which pawn owns this MovementComponent.
    //      UpdatedComponent: the component we move and update.
    //      ShouldSkipUpdate: Possibly skip update if moved component is not rendered or can't move.
    // If none own this component or there isn't anything to move or we have to skip this update, then return.
    if (!PawnOwner || !UpdatedComponent || ShouldSkipUpdate(DeltaTime))
    {
        return;
    }

    // Get (and then clear) the movement vector that we set in ACollidingPawn::Tick
    FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 150.0f;
    // If movement isn't nearly zero
    if (!DesiredMovementThisFrame.IsNearlyZero())
    {
        FHitResult Hit;
        // Move our UpdatedComponent by the given DesiredMovementThisFrame, and sets rotation to
        // UpdatedComponent->GetComponentRotation(), do a bSweep and store any hit on Hit.
        SafeMoveUpdatedComponent(DesiredMovementThisFrame, UpdatedComponent->GetComponentRotation(), true, Hit);

        // If we bumped into something, try to slide along it
        if (Hit.IsValidBlockingHit())
        {
            StopMovementImmediately();
        }
    }
};

The project is public in Github.

Maybe I don't understand something about Vectors.


texts: How can I create a six sided tillable perlin noise image?

texts:
I'm attempting to create a tillable hex shaped terrain map using c++.

As part of the process I'd like to use perlin noise, but it seems that in order to make it tillable I'll need to generate it 5 dimentionally and take a "circle" from it (if you know another way please let me know, I'm basing my theory on this post: https://ronvalstar.nl/creating-tileable-noise-maps by Ron Valstar) creating three cylinders that together make up the image

I've coded my own 2d perlin noise function but getting to 5d seems like a whole different beast

Unless anyone knows of one that already exists, I think I'll have to write my own library for generating the noise. I'm working on c++, and while I've seen a few perlin noise libraries I haven't seen any with 5d. I can generate a 5d vector feild no problem but it's the actual linear algebra where I'm confused. It'd involve me doing some quin-linear interpolation and I have no clue how to even start on that. If anyone knows how to do this already or has any resources that could help I'd appreciate it.

in summary:
1) anyone know how to generate 5d perlin?
2) anyone know of a different method to tile a six sided image generated from perlin noise?


texts: Problems with collisions (using vector of instances)

texts:
I wrote a for loop to check every instance of the class Wall, only the the last instance in the vector properly works

hybrid.h
 void reactTo(Player* other)
 {
     if (react)
     {
         if ((other->back<front && other->front > front) && (other->y > foot && other->y < head))
         {
             other->goAhead[0] = false;
         }
         else
         {
             other->goAhead[0] = true;

             if ((other->front >= back) && other->back < back && other->y > foot && other->y < head)
             {
                 other->goAhead[1] = false;
             }
             else
             {
                 other->goAhead[1] = true;
             }
         }
     }
     if (other->foot <= head && other->head >= head && other->x > back && other->x < front)
     {
         other->goAhead[2] = false;
     }
     else
     {
         other->goAhead[2] = true;
         if ((other->head >= foot) && other->foot < foot && foot && other->x > back && other->x < front)
         {
             other->goAhead[3] = false;
         }
         else
         {
             other->goAhead[3] = true;
         }
     }
     if (other->front > back && other->back <= front && other->head < head && other->foot > foot)
     {
         R = 0;
     }
     else
     {
         R = 1;
     }
 }

source.cpp
#include"hybrid/hybrid.h"

int main()
{
   setWindowSize(1500, 600);

   makeSequenceWall();//push back 5 Wall constructor

   Player p(300, 300,30,30,0.5,0,1,0);
   //------------
   slWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "HYBRID", false);
   while (!slShouldClose())
   {
               //----------
       p.move();
       p.render();//render the player

       for (int i = 0; i != 5; i++)//check the collision
       {
           wallSeq.at(i).reactTo(&p);
       }

       for (itr = wallSeq.begin(); itr != wallSeq.end();itr++)//render the wall
       {
           itr->render();
       }

       slRender();

   }
   slClose();
   return 0;
}

```


texts: Creating an electricity/lighting/tesla coil effect in a 2D XNA game?

texts:
I'd like to create beams of electricity between two points very similar to this video: http://www.youtube.com/watch?v=eMJ8-56L3Lc. The effect is so dynamic, with varying lengths and pseudo-random movement in-between the points, that I'm having trouble imagining how I'd accomplish such a thing. Is there any helpful information that might point me in the right direction?

I should note that I'm using the XNA 4.0 Reach profile, but custom shaders are okay because I'm not targeting the Windows Phone.


texts: Can I develop XNA using an Xbox 360 in India?

texts: I'm sending an Xbox 360 to a guy in India. Will he be able to play the games I'm sending along in India? Will Xbox Live work in India with my US-bought Xbox? Can he do XNA development on it?


texts: Can you store negative numbers with XNA HLSL?

texts:
I am trying to make a ripple effect with a HLSL shader, it works so far but I need to output negative numbers and that won't work for the calculations. Is there some way to do this with the SurfaceFormat class? By the way I am rendering 2 RenderTarget2D classes. This is how I calculate it:

float4 add = float4(0,0,0.5,0);
float4 input = tex2D( BaseSampler, Tex);
float4 cur = tex2D( RippleSampler, Tex);
float curY = 0;
float curX = cur.x;
float tempCurY = cur.y;

curY = (tex2D( RippleSampler, float2(Tex.x - pixelSizeX, Tex.y)).x + tex2D( RippleSampler, float2(Tex.x + pixelSizeX, Tex.y)).x + tex2D( RippleSampler, float2(Tex.x , Tex.y - pixelSizeY)).x +  tex2D( RippleSampler, float2(Tex.x , Tex.y + pixelSizeY)).x) * 0.5f - tempCurY;
curY *= damping;

if(curY < 0.01f){
    cur = float4(curX,curY  + input.x,0.5,1);
}else{
    cur = float4(curX,curY,0.5,1);
}

return cur;


texts:
So I am making a game in Libgdx using an isometric tiled map but when I set the texture filtering of the tiles to linear, black lines show up between all the tiles. This is caused because each tile blends with the tiles next to it.

I know many people have asked this before and the common answer seems to be add padding. I have padding but that doesn't help because then the tiles start blending with the clear pixels instead. That just turns the lines a different color.

Another option people say is to copy the pixels on the edge of each tile for padding, but unfortunately that only works for non-isometric maps. However when I use the tilemap preprocessor it works fine even with filtering, but the tilemap preprocessor causes many other issues so I don't want to do that.

How can I fix this? Somehow the tiledmap preprocessor does it fine but I'm not sure what that actually does other than adding padding. Any help is greatly appreciated!


texts: Easy method of obtaining texture coordinates for sprite sheet

texts:
In my (OpenGL ES 2.0 Android) game, I use 2 types of Sprite Sheets.  In one type all sprites/frames are of equal size and in the other they are all different shapes and sizes.

It is the latter one to which this question pertains.  Basically, I've created a sprite sheet and I currently use Paint.net to find the coordinates a particular frame sits at.  I then have to work out the texture coordinates by dividing the pixel by the width (for X) or height (for Y) so, if my image is 2048 x 2048 and a particular frame is at 300, 500, I work it out like so:

300/2048 = 0.146484375
500/2048 = 0.244140625

So, my X (or S) is 0.146484375 and my Y (or T) is 0.244140625.

I use the same method to work out the width and height.

I then code this using a method like so:

setTexCoords(0.146484375f, 0.244140625f, 0.048828125f, 0.048828125f);  //X, Y, Width, Height

When working with lots of sprites, this is a very tedious process.

The main problem however, is if I, at a later date, want to add sprites to the sheet and make it bigger to accommodate the extra sprites, I have to revisit every sprite and work out it's new texture coords based on the new bitmap size.

Is there any method I can use to make this process easier?

Even if it's just a program where I can hover the mouse over a bitmap and it tells me the texture coordinate (between 0-1).  Even that would take a little of the work out of it.

Any suggestions welcomed.

I have read a similar question on here however, none of the answers really helped


texts: Collision detection against large arbitrarily shaped textures

texts:
What is the most effecient way to do collision detection on strangely shaped textures in XNA? Here is an example texture:

As you can see, it is far from a perfect square. I want the player to collide with the brown parts and pass through the transparent ones.

How do I create a bounding box that wraps around irregular terrain? Should I create many smaller bounding boxes instead?


texts: Converting IntPtr to objects (here Raylib Material[])

texts:
I'm trying to apply a texture to the material of a Model but I could not figure out how to do it:
so I made a direct translation of the c code taken from examples:
(original from "Raylib [shaders] example - postprocessing shader" line 77)
model.materials[0].maps[MAP_DIFFUSE].texture = texture;

(my c# translation)
m_LP_SpookyTree = LP_SpookyTree.GetModel;
m_LP_SpookyTree.materials[0].maps[MaterialMapType.MAP_ALBEDO].texture = Raylib.LoadTexture("Ressource/Textures/PlaceHolders/mossy_rock_diff_1k.png");

According to the cs file on the repo, the "materials" definition is an Int pointer.
The problem comes from the Intptr, how could I get the material array from it?
thanks for your time.
PS: I've created an issue on Raylib.cs GitHub repo so if I get an answer on one before the other, I'll update accordingly

EDIT 1:
I've tried to change every IntPtr to the object it should actually point to regarding the comments in the source file, compile the lib, and imported it. unfortunately, it broke. so I don't think it's possible.

EDIT 2:
I've found this article talking about IntPtr to objects (vice versa)
https://stackoverflow.com/questions/728105/how-to-convert-an-intptr-back-into-an-object
I've implemented it like so:
public static object pointerToObject(IntPtr pMapping, Type type)
{
    return Marshal.PtrToStructure(pMapping, type);
}

but now I get this error:
System.MissingMethodException : 'No parameterless constructor defined for type 'Raylib_cs.Material[]'.'

PS: The new code:
Material[] materials = (Material[])PointerManipulation.pointerToObject(m_LP_SpookyTree.materials,typeof(Material[]));
MaterialMap[] materialMaps = (MaterialMap[])PointerManipulation.pointerToObject(materials[0].maps, typeof(MaterialMap[]));

materialMaps[(int)Convert.GetTypeCode(MaterialMapType.MAP_ALBEDO)].texture = Raylib.LoadTexture("Ressource/Textures/PlaceHolders/mossy_rock_diff_1k.png");


texts: Organising data of a turn-based strategy

texts:
I'm intermediate in Java but novice in everything which is on the server-side.
I've set myself a task to rewrite an old game, so learning Java is more fun.
It is a space turn-based strategy. The original was called Stars! (I heard that Master of Orion is somewhat similar). Basically players assign their orders to ships and planets and then submit a turn to server, where a new turn is generated.

I suppose, I will have a lot of objects (ships, fleets, planets and so on), each of them will have some properties (XY position, orders, HP etc.). When generating a turn, the server will have to cycle through all the objects and perform tasks with each one (move a ship, unload a cargo for instance).

The question is:
How should I organize entities, ships for example, so it is easy to process them. Should I store them in a database? Perhaps there is some sort of a best practice for tasks like this?

If I assume, that ships will be stored in a database. Then, each player will send a file with orders to the server. The server will put everything into a database. When all the players have submitted their turns, the server will cycle through everything in the database and generate a turn. Will this be a good way to do this?


texts: Which API for cross platform mobile audio?

texts:
This question focuses on the API's available on phones.

I'd been planning to use OpenAL in my game for maximum portability.  It runs great on Linux so I can quickly iterate while developing as well as leverage the desktop's superior debugging tools.

However I've recently heard that Android doesn't support OpenAL well.  Instead they've gone with an OpenSL ES library.

What I'm looking for is a free Audio library that I can use with minimal custom code on iPhone, Android, and my Linux desktop.  Does such a library exists?

Some extra details:
The game is written in C++ with custom minimal front ends, e.g. ObjC for iPhone, Java for Android, and SFML for desktops.  I'm using OpenGL ES for portability as iPhone doesn't support the more advanced OpenGL APIs.


texts: Car (or other "object") acceleration and braking: how to?

texts:
I'm not good in math so I'm here to ask you how to manage, in a simple 2d game, the car acceleration and braking.

I'm trying to develop it (as a hobby) in c# and sdl.net.


texts: XNA how to draw some sprites tiled/wrapped and others not?

texts:
I already have:

mySpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

and take care to draw all my sprites in order.

I now want to draw some textures tiled. Do I have to create another SpriteBatch and call:

mySpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.LinearWrap, DepthStencilState.Default, RasterizerState.CullNone);

To draw my tiled textures? But won't these tiled sprites be drawn on top the ones already drawn with the previous SpriteBatch?

What I would really like is to be able to do is draw some sprites normally and some tiled using the same SpriteBatch then my ordering wont be messed up. Is this possible? I tried:

GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;

In my first and only SpriteBatch but got the InvalidOperationException:

  Cannot change read-only SamplerState. State objects become read-only the first time they are bound to a GraphicsDevice. To change property values, create a new SamplerState instance.


texts: Problem loading content in WinForms using XNA

texts:
I'm currently having trouble implementing loading content with the content pipeline into my WinForm application. I'm using the "WinForms Series 1: Graphics Device" sample provided by microsoft.

By simply creating a project, copying over the classes, creating a both content projects like in the sample worked all fine. But what I really want is use my XNA Game Project and it's Content Project to be used so I can run simple simulations inside my editor with it's code and graphics.

I thought it would be really simple since it appears to be the same structure except this time the games project has some code in it. But it seems like it doesn't, if I try to load some font or a sprite it gives me the classic red cross and a console entry telling me it can't load my asset. However, it's clearly on the Content directory in the build.


texts:
I just started using events, and got stuck a little. I have a problem with the following code:

class InputHandler
{
      public delegate void Shooting();
      public static  event Shooting OnShoot;

      void Update()
      {
            if( fireButtonPressed)
                OnShoot();
      }
    // Rest of the class.
}

class Weapon
{
     void Shoot()
     {
         //Do the shooting.
     }

    void OnEnable()
   {
         InputHandler.OnShoot += shooting;
   }

   void OnDisable()
   {
         InputHandler.OnShoot -= shooting;
   }
}

class UI
{
     void UpdateBulletsCount(int bulletsLeft, int magSize)
     {
         //Update the UI.
     }

    void OnEnable()
   {
         InputHandler.OnShoot += UpdateBulletsCount; //  clearly can't do that.
   }

   void OnDisable()
   {
         InputHandler.OnShoot -= UpdateBulletsCount;
   }
}

My UI class has a method to update the bullet count when you fire, reload or change the weapon. As you can clearly see, it takes in different parameters.  This allows me to change the UpdateBulletsCount() to accept no parameters, and find the weapons info through GetComponent or Find, in order to update UI.

However, then the UI class will depend on the Weapon class, which breaks the separation of classes and components that I am trying to achieve. Is there any way to use events without breaking class and component separation?


texts: Rectangle in object-layer has wrong coordinates in game

texts:
I extended the SuperKoalio LibGDX Example about an Tiled Object Layer in the Tiled Level-Editor and draw a rectangle on this layer.
Now I would like to draw this rectangle in my game using the ShapeRenderer debugRenderer from the above SuperKoalio Example.

So, I changed the renderDebug method from example:

private void renderDebug () {
    Gdx.graphics.getGL20().glLineWidth(1.5F);

    // I think something is wrong with this:
    debugRenderer.setProjectionMatrix(camera.combined);

    debugRenderer.begin(ShapeType.Line);

    //Removed the rendering of the rectangles around ground and player

    // I added the object layer "objects" in the level1.tmx map
    // And this code:
    MapLayer objectLayer = map.getLayers().get("objects");
    debugRenderer.setColor(Color.RED);
    Rectangle rect;
    for(MapObject mo : objectLayer.getObjects()) {
        rect = ((RectangleMapObject) mo).getRectangle();
        debugRenderer.rect(rect.x, rect.y, rect.width, rect.height);
    }

    debugRenderer.end();
}

Running this looks like:

The rectangle is missing in game and I can't figure out why.
Removing the setting of the ProjectionMatrix camera.combined makes the rectangle visible but it doesn't stick on the map and scrolls with the player. The position is a little wrong, too.

You can find my gist with modified example here.

How do I render this rectangle correctly? Thanks in advance!


texts: How to move objects with different y positions by a certain number of units

texts: As seen in the image below, I have game objects with different y positions. I would like to select and change their y position by say, 2 units downwards while maintaining the gap. Please note I want this to be done through the inspector. I tried adding 2 units, but this just put all four objects on the same line. How can I achieve this?


texts:
I'm looking into implementing AI in my 2D side-scrolling platformer, and I'm looking into using algorithms such as A*. For many kinds of pathfinding, we need some sort of grid or systems of nodes or polygon areas. My problem is that I am using Box2d for physics and I am not sure how best to create a structure that my AI can use besides placing individual nodes manually (something I really want to avoid) and using some sort of steering behavior.

My level design is tile-based with each tile being about half of the height/width of my main character. The tiles are not all square (some are sloped). I'd like to have a system that can see what the terrain looks like for pathfinding and also keep track of the positions of other actors such as enemies. I'd like to avoid directly placing any nodes into my level design except for possible endpoints or goals.

This question is related: How do you do AI path following within a 2d physics engine like farseer/box2d?, but it doesn't specify what kind of structure I could use instead of a list of nodes. I'm looking for some kind of grid or type of BSP that I can query for algorithms like A*.

EDIT: I am looking for a data structure that meets the following requirements:

Can be searched by algorithms like A*
Can keep track of objects that move around
Can keep track of objects of different shapes and sizes
Does not require me to manually create paths or place nodes

When I first load my level, I have a 2D array (actually just a width, height, and string of ints), but this doesn't allow me to track objects that move not to mention other shortcomings.


texts: Implicity of "Objects" in component based design

texts:
For a while, I have mostly been using "standard OOP" (inheritance heavy, tree structure, etc.) styled designs for my Game Development needs. However, for my current project I am trying to shift over to a component-based design (This is all at a hobby level, so time/money/productivity speed are not important ATM.) However, while researching into component based designs, I am confused about how the concept of "objects" are implement.

From what I can understand, there are 2 schools of thought in regards to the relationship between components and objects. One paradigm seems to implement objects as classes that simply serve as "containers" for holding components that interact with another. However another paradigm seems to get rid of the concept of an object itself, with objects only existing implicitly. (however, I fail to understand how synchronization issues don't appear. If anybody could also explain this, that would be very helpful.)

Regarding these 2 ideals, are there any major benefits (performance, usability, etc.) to choosing one paradigm over another?


texts: MonoGame - Fuzzy Pixels When Drawing (2D)

texts:
I apologize if this has been answered somewhere; I spent quite awhile searching but couldn't find an answer.

I have any issue with my 2D sprites being drawn to the screen - either the non-moving or moving sprites will appear to have a sort of "fuzzy" texture to them. Now, this isn't an issue with me drawing to integer positions - after a bit of debugging, I found out this was an issue with my camera - it'll jump between, say, (79, 179) and (81, 181). The number is arbitrary, but it's always two pixels.

The camera follows the player's sprite, unless the player happens to be near the edge of the map - in which case, the player can move freely without the camera chasing it (so the camera doesn't show the void space outside the world). During this "free roam" space, when moving, the static entities/sprites appear normal, but the player's sprite appears fuzzy (and if the camera is following the player, the static entities appear fuzzy while the player entity appears normal). If I get the player to move around enough, what happens is that I'll be able to see the console printing out the odd values for the camera's position (as stated earlier).

My camera's update code:

    public void Update(Entity followEntity)
    {
        Vector2 moveToPos = new Vector2((int)followEntity.Position.X - 400, (int)followEntity.Position.Y - 300);
        Console.WriteLine(position);
        position = Vector2.Clamp(moveToPos, MinBounds, MaxBounds);
        transform = Matrix.CreateTranslation(-position.X, -position.Y, 0);

        inverseTransform = Matrix.Invert(transform);
    }

My player's update code automatically casts its position to an int (since Vector2's are stored in floats), but I cast it explicitly in this code while I was debugging. I also tried setting position's x and y values to ints after it clamps the value, but that didn't have any effect.

In case it helps, my draw method is as follows:

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

        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, playerCamera.Transform);
        tileMap.Draw(spriteBatch);

        foreach (Entity e in Entity.LiveEntityList)
            e.Draw(spriteBatch);

        spriteBatch.End();
        base.Draw(gameTime);
    }

If there's anything information I could add to help you help me, please let me know. Thank you for your time!

Edit: the - 400 and - 300 values in my camera's update code are purely hardcoded values to determine the center of the screen since I was running it in 800x600, in case anyone was curious or needed to know.

As requested, a screenshot:

You can see the corners of the two squares slightly overlapping; it bounces between this and being one pixel away. The desired behavior would look as follows:


texts: Unity uNet Low Level API - which values should I snyc?

texts:
I am using unitys unet low level api: TransportLayer.

I send my own message by converting strings to byte-arrays.

I want a server authoritive setting, so that I can try to implement my own client side prediction.

I am also using unitys physics2d, rigidbodies and so on.
I thought about to move the rigidbodies with it's velocity.

I wonder which values I should send from client to server and backwards, to avoid the rigidbody jittering.

I know that I cannot simply send the clients position to the server, because that will cause the jittering "effect".

Would be nice, if anyone can give me guidance.

Thanks :)


texts: Managing lists of different types of entities  - is there a better way?

texts:
I am developing a 2D space game for mobile devices, but it gets realy complex and my solution is realy confusing and produces lots of repeated code segments.

I hava a world class in which i have multible lists of different object like:

List<Enemy> enemys;
List<Projectile> projectiles;
List<Collectable> collectables;
List<Asteroid> asteroids;
List<Effect> effects;
..

Each list gets updated by the world class. but thats not all..
Each enemy has a list of engines, and list of weaponlunchers which gets updated by the enemy. Now each engine adds some fire effects to the world list 'effects', and each weaponluncher adds projectiles to the world list 'projectiles'.
All these classes have different parameter, so i need an extra update AND extra render function for each class.

At least they are all childs of 'GameObject' which provides them basic things like position, velocity and acceleration vectors, bounding Polygons and functions like applyForce and a finite state machine

Is there a better or more common way to do this? like one catch-all class which contains all possible parameters and methods for all different objects. (i think this would produce even more confusing code)