texts: How to move a Line Renderer as its game object moves

texts:
I created an empty game object and added a Line Renderer component to it through a script. I thought that once I adjust the position of the game object, it would do likewise for the line rendeder, but that is not the case.

I tried useWorldSpace = false but it totally changed the positions making the following points a straight line, though I was able to move the game object to to the line.

public Vector3 beginPos = new Vector3 (-1.0f, -1.0f, 0);
public Vector3 endPos = new Vector3 (1.0f, 1.0f, 0);

Is there a way I can convert points to input what I am more familiar with (so that points like the above points don't create a straight line) or should I be approaching the problem in a different way? I am open to a different approach.

UPDATE

I think I left an import detail. I'll be using lines made with line renderer to create shapes. So I need to be able to be able to move the lines around to move the shapes so I don't have to always recalculate the start and end points for the lines.


texts: Prefab instantiate or create gameobject at runtime?

texts:
I'm developing a skill system for a client-server game, all available player's skills server send to it, then client load it and put it to a spellbook.
So I stuck in loading stage, how for performance and/or memory will be better:

Save all spells in a bunch of prefabs and then just instantiate them
Create JSON/binary/etc file, parse them and create a gameobject at runtime

From the side of editing, both methods are equal.


texts: How can I get post-processing effects with pygame?

texts:
I'd like to be able to make the screen like blurry and wavy, like when a player enters a portal in Minecraft.

How would I make this with pygame?


texts: Unity post processing Bloom lags on mobile

texts: I made my (first) game today and noticed, that it looked kind of boring, so I decided to add some bloom to my camera and it was looking waaay better. The only problem was the performance, it dropped down from constant 60 fps to like 20-30, I looked it up in the profiler to be sure and yep, it was the post-processing, I saw mobile games which had post-processing including bloom, but these games never lagged on my phone. My phone has pretty good specs for a phone (Samsung Galaxy M20) so how do I make my post-processing performant, are there some special settings I have to make or is it just my phone?


texts: In some games, we just let the main() loop be the Player object or Table object?

texts:
I was thinking that let's say if there is a game of Blackjack or MasterMind, then we should have a class called Dealer or ComputerPal, which is how the computer interact with us (as a dealer for Blackjack or as the person giving hints for MasterMind).

And then there should be a Player object, and the way to play one game is

aPlayer.playGame

but I noticed that a book was just using the main() loop to act as the player (or as the Controller of the game), calling the Dealer methods to dealer the cards, ask for player's action, etc...

1) Is this just a lazy way to model all the proper objects?

2) If more objects are to be added, who should call the aDealer.dealCards and then ask for aPlayer.askForAction?  (because it is strange to let the Player handle all the logical steps).  Should there be a Table object that handle all these logic and then to play one round of game, use aTable.playGame?  What is a good object design for such game?


texts:
Language: C# w/ XNA Framework

Relevant and hopefully helpful background info:

I am making a library using the XNA framework for games I make with XNA. The Library has a folder(Namespace) dedication to the GUI. The GUI Controls inherit a base class hooked with the appropriate Interfaces. After a control is made, the programmer can hook the control with a "Frame" or "Module" that will tell the controls when to update and draw with an event. To make a "Frame" or "Module", you would inherit a class with the details coded in. (Kind of how win forms does it.) My reason for doing this is to simplify the process of creating menus with intractable controls. The only way I could think of for making the events for all the controls to function without being class specific would be to typecast a control to an object and typecast it back. (As I have read, this can be terribly inefficient.)

Problem:

Unfortunately, after I have implemented interfaces into the base classes and changed

public delegate void ClickedHandler(BaseControl cntrl);

to

public delegate void ClickedHandler(Object cntrl, EventArgs e);

my game has decreased in performance. This performance could be how I am firing the events, as what happens is the one menu will start fine, but then slowly but surely will freeze up. Every other frame works just fine, I just think it has something to do with the events and... that is why I am asking about them.

Question:

Is there a better more industry way of dealing with GUI Libraries other than using and implementing Events?

Goal:

To create a reusable feature rich XNA Control Library implementing performance enhancing standards and so on.


texts:
I have to develop a game with a dynamic destruction of the map, I searched the internet and even looked at some questions regarding this topic on this Website, but they did not help me much out.

I made the map with tiled and used box2d to make collision between the game objects. As a game engine we have to use Libgdx, but I dont know how to start as I had never develeped a game before, can someone give me any tipps how I could start?

with regards,


texts: how to detect touch on instantiated prefabs in unity

texts:
I have instantiated objects (that have collider2D attached) in a grid of 9x13. Now I want to detect a touch on each object individually. I am confused about how to do it. Either write script separately on prefab or do it in my gameController script? Also what is the method to do it?

Here is my code for instantiating:

    public GameObject bubble;
    int row;
    int col;
    float x;
    float y;

    void Start ()
    {
        x = -2.4f;
        y = 2.95f;
        row = 13;
        col = 9;

        Vector2 position = new Vector2(x, y);

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                Instantiate(bubble, position, Quaternion.identity);
                position.x += 0.6f;
            }
            position.x = x;
            position.y -= 0.6f;
        }
    }


texts: Where is the LocalizedFontProcessor in XNA?

texts:
I tried this tutorial to localize my XNA Windows Phone game, but I can't find the LocalizedFontProcessor in the drop-down list. Why is the LocalizedFontProcessor missing in the drop-down list? What is wrong?

In this picture you can see that the LocalizedFontProcessor is missing in the drop-down list:

Is there another way to localize a Windows Phone game?

Edit: Here is my LocalizedFontProcessor class

namespace LocalizationPipeline
{
[ContentProcessor]
class LocalizedFontProcessor : ContentProcessor<LocalizedFontDescription,
                                                SpriteFontContent>
{
    /// <summary>
    /// Converts a font description into SpriteFont format.
    /// </summary>
    public override SpriteFontContent Process(LocalizedFontDescription input,
                                              ContentProcessorContext context)
    {
        // Scan each .resx file in turn.
        foreach (string resourceFile in input.ResourceFiles)
        {
            string absolutePath = Path.GetFullPath(resourceFile);

            // Make sure the .resx file really does exist.
            if (!File.Exists(absolutePath))
            {
                throw new InvalidContentException("Can't find " + absolutePath);
            }

            // Load the .resx data.
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load(absolutePath);

            // Scan each string from the .resx file.
            foreach (XmlNode xmlNode in xmlDocument.SelectNodes("root/data/value"))
            {
                string resourceString = xmlNode.InnerText;

                // Scan each character of the string.
                foreach (char usedCharacter in resourceString)
                {
                    input.Characters.Add(usedCharacter);
                }
            }

            // Mark that this font should be rebuilt if the resource file changes.
            context.AddDependency(absolutePath);
        }

        // After adding the necessary characters, we can use the built in
        // FontDescriptionProcessor to do the hard work of building the font for us.
        return context.Convert<FontDescription,
                               SpriteFontContent>(input, "FontDescriptionProcessor");
    }
}
}


texts: Any good pathfinding algorithm for lots of different speed zones? NavMesh seems not work

texts:
I have a terrain map with lots of different areas: roads, grass, swamp, forest, mountains. Each has different speed for the player. The map is continuous 3D map, not grids.
Given a start & end point, I want to find the shortest time path instead of shortest distance path.
I tried NavMesh with area cost as the standard solution. But it could not solve system with different speed zones correctly.
For example, given a simple NavMesh graph, each square is a nav mesh (you can think of two triangles if you like), gray is road, which has fastest speed; green is swamp, which has slowest speed. Given the start point s1 to end point e1. The NavMesh algorithm will give the direct path p1 since it's translating within one mesh, no matter what the area cost is. But the actually shortest time path would be p2: get out of swamp, then travel along the road, finally get into the swamp again.

Another example is s2 -> e2. The actually shortest time is the direct path, but the NavMesh would give the red path since each mesh only count once, without considering the path length.
So for my use case, what would be a good path finding algorithm?


texts: Where can I find an open source component-based game?

texts:
Check that link:
Evolve Your Hierarchy

I'm interested in that kind of game development, and the theory looks nice! But I want taking a look in the source code of some game developed following that methodology. It will be good if it's simplistic (or even educational!), and better if it's coded C++ or C#. Thanks!


texts: Why am I unable to move a player that extends image?

texts:
I wanted to create a simple game where I will be able to move a player image horizontally. I am using Screens (at least trying to do so) and created the below:

public class GameScreen implements Screen {

    private JumpingKitten jumpingKitten;
    private Stage stage;
    private OrthographicCamera camera;
    private SpriteBatch spriteBatch;
    private Player player;

public GameScreen(JumpingKitten jumpingKitten) {
    this.jumpingKitten = jumpingKitten;
    this.createCamera();
    this.stage = new Stage(new StretchViewport(1026.0f, 768.0f, this.camera));
    this.spriteBatch = new SpriteBatch();
    Gdx.input.setInputProcessor(this.stage);
    init();
}

private void init() {
    initPlayer();
}

private void initPlayer() {
    player = new Player();
    stage.addActor(player);
    stage.act();
}

private void createCamera() {
    this.camera = new OrthographicCamera();
    this.camera.setToOrtho(false, 1026.0f, 768.0f);
    this.camera.update();
}

@Override
public void render(float delta) {
    this.clearScreen();
    handleInput();
    this.camera.update();
    this.spriteBatch.setProjectionMatrix(this.camera.combined);

    spriteBatch.begin();
    stage.draw();
    spriteBatch.end();
}

private void clearScreen() {
    Gdx.gl.glClearColor(0.15F, 0.15F, 0.3F, 1.0F);
    Gdx.gl.glClear(16384);
}

private void handleInput() {
    if(Gdx.input.isKeyPressed(Input.Keys.A)) {
        player.STARTING_X -= 50 * Gdx.graphics.getDeltaTime(); // STARTING X incorrect
        System.out.println("A is pressed"); // shown in console
    }
    if(Gdx.input.isKeyPressed(Input.Keys.D)) {
        player.STARTING_X += 50 * Gdx.graphics.getDeltaTime();
    }
}

And below is the player class:

public class Player extends Image {

private static final int PLAYER_WIDTH = 119;
private static final int PLAYER_HEIGHT = 136;

public static int STARTING_X = 100;
public static final int STARTING_Y = 100;

public Player() {
    super(new Texture("Cat_Idle_1.png"));

    this.setOrigin(100, 100);
    this.setSize(PLAYER_WIDTH, PLAYER_HEIGHT);

    this.setPosition(STARTING_X, STARTING_Y);

}

Even though I have completed some simple tutorials, I am unable to retrieve the x coordinate of the player object. This is stopping me from translating the player object along the x axis. Can someone explain what I am doing wrong, here? I honestly think that I jumped into something I shouldn't have.


texts:
So, I was annoyed by how the HUD for my GameState was very pixel-ated and I wanted to change that through the use of anti-aliasing. However, it works with a small exception:

It adds all these lines to the HUD, which is not what I want at all, is there a way to prevent this from occurring?

Here's what it looked like before anti-aliasing:

Also, here's the code:

    public void render(GameContainer container, StateBasedGame game, Graphics graphics) throws SlickException {
    graphics.setAntiAlias(true);
    renderOverlayGui(graphics);
    renderGui(graphics);
    graphics.setAntiAlias(false);
    renderIcons(graphics);
}

private void renderIcons (Graphics graphics) {
    graphics.drawImage(imgHeart, this.radius - 4, 1);
    graphics.drawImage(imgCoolDown, this.radius - 4, 18);
}

private void renderGui (Graphics graphics) {
    graphics.setColor(GameColour.brown);
    graphics.fill(guiCircle);
    graphics.fill(guiBox);
}

private void renderOverlayGui (Graphics graphics) {
    graphics.setColor(Color.black);
    graphics.fill(guiOverlayCircle);
    graphics.fill(guiOverlayBox);
}


texts: Stopping an object after applying an impulse or force?

texts:
I'm having a small issue where after applying an impulse or force it is impossible to actually get an object to stop, i.e. a velocity of zero.

This code is run every 1 / 60 of a second:

void RigidBody::Update(double deltaTime) {

    double mass = GetMass();
    //If static body, do nothing.
    if(Math::IsEqual(mass, 0.0)) return;

    Vector2D F;
    Vector2D total_forces = std::accumulate(_curState._forces.begin(), _curState._forces.end(), Vector2D());
    Vector2D total_impulses = std::accumulate(_curState._impulses.begin(), _curState._impulses.end(), Vector2D());
    F = _curState._gravity + total_forces + total_impulses;
    _curState.ClearImpulses();
    SetAcceleration(F / mass);
    SetVelocity(GetVelocity() + GetAcceleration() * deltaTime);
    SetPosition(GetPosition() + GetVelocity() * deltaTime);

}

RigidBody::SetAcceleration(const Vector2D& acceleration) {
    _prevState.SetAcceleration(_curState._acceleration);
    _curState.SetAcceleration(acceleration);
}
//Similar for RigidBody::SetVelocity and RigidBody::SetPosition...

If I apply an impulse, say (-1.0, 0.0), the object's acceleration changes by -0.012 or -0.011 instantaneously and only once then reverts to (0.0, 0.0), which then changes the velocity to (-0.012/-0.011, 0.0). Equal and opposite changes in acceleration causes rounding errors to accumulate to the point where the velocity will never be zero and the object will never stop.

Similarly, if I apply a force, (-1.0, 0.0), the object's acceleration changes to (-1.0, 0.0), equal and opposite forces applied so the acceleration changes to (0.0, 0.0) works but the velocity changes so minutely that again, the object will never stop. (The closest I've ever gotten it was (0.009, 0.0) )


texts:
After creating a tree (Scots Pine) in SpeedTree Cinema v7.1.1 I exported it as a .FBX ascii file to Unity 5 and I encountered a problem; the leaf material, while viewing it in Unity 5, can only be seen when I view the tree from the top, but when I view the tree from the bottom or the side, the leaves dissapear, they're not visible anymore, but on the other side, I can view the leaves of the tree from any angle in SpeedTree Cinema v7.1.1.

I don't know if the problem is one of the following:

The way I export the tree (.FBX ascii)
The way the texture is saved (.tga, .jpg, .png)
The material settings (in SpeedTree or Unity)

So you can better understand, i'll show the following images:
Description of images is below

(Image 1.) Here are the setting of how I export the tree and you can also see the clearly see the leaves from all angles.

(Image 2.) Here is my tree (the tall one, Scots Pine) and you can't see the leaves from underneath and the material displayed on the right belongs to the leaves of my tree (the tall one, Scots Pine). The tree to its side(the small one) is how I would like the leaves to look ( i didn't make the small tree).

(Image 3.) In here you can see the leaves of my tree (tall one, Scots Pine) from the top, and next to my tree is another one (not my tree) which is how i would like my trees leaves to look. The material displayed on the right are from the small tree (not my tree).

Any help is appreciated, thank you.


texts: UNITY - Huge amount of GRAPHICS in RTS Tiled game

texts:
after year of development and week of unsuccessful optimization I turn for a help from you, guys.

So, my game is turn-based strategy with hexagon map.
One hexagon consists of one texture for hexagon tile type and seven subtiles, which carry spriterenderer with graphics like piece of town. So if soldier steps on the subtile, the graphics of subtile hide.

On good machines like mine, if I zoom out maximally (45 orthographic size) on 1920x1080 and have visible around 18x16 tiles I get solid 160-200 FPS at MAX details, but on my laptop I barely get 25FPS on 1280x720 and LOW details. Each tile has resolution of 636x499.

I have tried:

Simple shader on SpriteRenderer supporting transparency, just merging    texture with color (This had those best results of 160-250FPS at    HIGH-END and 25FPS on LOW-END)
Creating separate material for each    subtile and replacing SpriteRenderer with Quad mesh, so those    subtiles are statically batched or GPU batched (but I guess they did    not batch at all, because frame debugger showed that sometimes more    fo the same pieces got rendered and then sometimes just one)

So this is just the 50x50 game, when I start large map, like 120x100, it's not really that worse, so I think the problem is just in the graphics and not in the amount of objects.

What are your suggestions I should try to get better performance on LOW-END devices? Do you think that manual GPU-instancing would make it faster? I think, there would be a lot of trouble maintaining which graphic to render and which not.


texts:
I have to develop a game for my Graphics Course. I came across this video on the net.

http://www.youtube.com/user/stanfordcs248

I want to know how are the hazy/smoky effects which trails along with the cube is rendered using OpenGL and c++?


texts: How to scale a sprite on x axis to touch the point without changing pivot?

texts:
I have a sprite. The pivot is at random point.

I want to increase the sprite's scale on the x axis, without moving the pivot, until its edge touches a point at right.

I have a method to set/add size. I calculate a distance from the sprite's edge to the point at the right and add it as a size.

The problem is the sprite scale increases its size in both directions of the x axis (left and right), considering the pivot is not at the left edge of the sprite.

How can I scale the sprite while keeping the left edge where it is?

I have:

I want to get:


texts: How do I calculate the new Quaternions from translated points?

texts:
The code below is for a rag-doll using Verlet method, I have the correct points (or joints) positions, I just need the correct Quaternions, otherwise the resulting model looks like in the picture, I'm constraining the body to the bind pose on purpose for testing purposes.

Based on the two points, their position and quaternion, what will the new Quaternion be for each translated point?

struct Point
{
    XMVECTOR position = { 0,0,0 };
    XMVECTOR quaternion = { 0,0,0,-1 };
};

Point p1;
Point p2;

p1.position += { 0.0f,0.3f, 0.1f };
p2.position += { -1.0,0.3f,0.1f };


texts: Synchronizing clients with a server and with each other

texts:
What is the best way for keeping all clients synchronized with a server and with each other?

Currently, we have two approaches in mind:

When a client sends something to the server, the server immediately sends out messages to all clients, which react immediately.
Introducing some time delay, whereby the server sends out messages to all clients, with the directive, "act upon this at time t.

The second approach seems like it would more likely keep the clients all in better synchronization (since it caters for some degree of lag); but I wonder whether responsiveness would be lost to too high a degree (i.e. the user clicks 'jump' and there is a noticeable gap between pressing the button and actually jumping).

There is also the possibility of having clients calculate their own position (and not wait for servers to say "you have jumped"); but because of the inevitable lag, clients would get very out-of-sync.

Then there's the whole TCP vs. UDP question; because we want it fast, but I'd also hate for the server to say you're in a completely different location than you thought you were.

With all of these competing demands, it all gets very uncertain how we should approach this issue. Which of these approaches (or any other) would be best for keeping clients and server all in sync? Which ones are actually used in the industry?


texts: How to properly handle sending arrow-key movement data to a authoritative server?

texts:
I've made a little C# server which receives UDP packets and shows me the incoming information. I want to make an authoritative server in C# which simulates character movement and interaction in a 2D real-time world and sends information back to a Unity game client where the information is then represented.

My question is: How does my server know how long a button is pressed in real-time (example: right arrow key to move character right)?

My guess is that the client would send a UDP packet to the server on-key-press saying move-this-direction. The server would then simulate the character moving and new positional information is constantly sent back. When the Client releases the key a new UDP packet is sent to the server saying the movement key has been released thus stop-moving-this-direction. BUT the problem is UDP unreliability and the lag between letting the key press up, and the server knowing that the key press is up; which would make the character keep moving for a period of time after letting go of the key - is this solved with proper movement interpolation?.

Any ideas or information sources how to properly handle sending arrow key movement data to a authoratative server?


texts: How to expand the limit of screen mouse access for FPS side rotation

texts:
I started coding in Godot and i have a working FPS controller but the problem is that when i move my mouse sideways , it cannot move my sight beyinid that side of my screen , in other words the movement of my charecter is limited by the size of my screen , how to prevent this
Rotation code
func _input(event):
if event is InputEventMouseMotion:
    head.rotate_y(deg2rad(event.relative.x * -mouseSensitivity))
    camera.rotate_x(deg2rad(event.relative.y * -mouseSensitivity))


texts: XNA Calculate two points of triangle with given Z

texts:
I want to calculate the two points of a 3D triangle that have a specified Z coordinate. I guess the way to do this would be to somehow create a plane which is perfectly flat with my given Z coordinate and then calculate where the triangle intersects with it (or is this wrong).

If you know how to do this in any way please help. I have searched for but have not really found anything that seems to work.


texts:
I'm making a simple, non-networked game. There are two players and a ball. In implementing the AI for the second player, I've run into a huge problem predicting where the ball will hit the ground. Either I've made a mistake in the physics engine or in implementing the prediction itself. I wrote the physics engine, and while it works visually as I expect it to, I won't rule it out as a suspect. First I'd like to make sure I haven't made a mistake in the prediction code. Here's what I have found so far:

I print the predicted time to impact and the accumulated time in each frame. The time predicted for impact is way off.

tti: 0.678233
total time: 0
.
.
tti: 0.0108339
total time: 0.94969
[ball] ground collision

The code for predicting is in two functions.

double nextBallCollisionWithGround(Ball *ball, double groundHeight) {
    double timeToImpact = quadraticSolver(kGravity, ball->velocity().y, ball->position().y - ball->radius() - groundHeight);
    std::cout << " tti: " << timeToImpact << endl;
    double groundPos = -3.;
    if (timeToImpact > 0) {
        groundPos = ball->velocity().x * timeToImpact + ball->position().x;
    }
    return groundPos;
}

double quadraticSolver(double a, double b, double c) {
    double ans = -1.;
    double det = (b*b) - (4.*a*c);
    double t1, t2;
    if (det > 0.) {
        t1 = (-b + sqrt(det)) / (2. * a);
        t2 = (-b - sqrt(det)) / (2. * a);
        if (t1 > 0.)
            ans = t1;
        if (t2 > 0.)
            ans = t2;
    }
    return ans;
}

If there's no problem in these functions, I can include the relevant parts of the physics engine to see if the problem is there.


texts: How can you make a jump to a point using the Character Controller?

texts:
I found an example with which the CharacterController can jump, but it does not work to remake it so that it jumps to a certain point/distance, and the jumpHeight itself was calculated for speed and gravity, I found this article on Wikipedia, but I don't even know why to begin.
public class ExampleClass : MonoBehaviour
{
    public float speed = 6f;
    public float jumpHeight = 8f;
    public float gravity = 20f;

    private Vector3 moveDirection = Vector3.zero;

    CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {

        if (controller.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }

    // Method for jump, calling from other script.
    void Jump(float pointX)
    {
    }
}

I can't find examples for the Character Controller, although I did find one for the Rigidbody.


texts: I am making an FPS in XNA. I cannot seem to make a FPS camera that I can move Forward, Back, Side to Side using the keyboard. How do I do that?


texts: Changing the color of some fragment of a texture using shaders

texts:
Declarative programming language QML allows to connect the elements, their properties with universal variables in shader programs description. For these purposes there is such elements as ShaderEffectItem, for instance. Here, for example, we define a certain image image.jpg. And in the source property we set just that this image any will change in the image and further this property is set already in the fragment shader program description fragmentShader as uniform sampler2D source. qt_TexCoord0 defines initial coordinate a texture. We receive there gray color on all texture scalar product lowp float gray = dot (textureColor, vec4 (0.299, 0.587, 0.114, 0.0)); also we install color of a fragment in an output variable gl_FragColor.

....
Item {
    id: main
    Image {
         id: img
         source: "images/image.jpg"
      }

    ShaderEffectItem {
       id: effect
       property real ratio: 1.0
        property variant source: ShaderEffectSource {
             sourceItem: img;
             hideSource: true
        }

        fragmentShader:
          "
          varying highp vec2 qt_TexCoord0;
          uniform sampler2D source;
          uniform highp float ratio;
          void main(void)
          {
            lowp vec4 textureColor = texture2D(source, qt_TexCoord0.st);
            lowp float gray = dot(textureColor, vec4(0.299, 0.587, 0.114, 0.0));
            gl_FragColor = vec4(gray * ratio + textureColor.r * (1.0 - ratio), gray * ratio + textureColor.g * (1.0 - ratio), gray * ratio + textureColor.b * (1.0 - ratio), textureColor.a);
         }
         "
    }

        SequentialAnimation on ratio {
            id: ratioAnimation
            running: true
            loops: Animation.Infinite
            NumberAnimation {
                easing.type: Easing.Linear
                to: 0.0
                duration: 500
            }
            PauseAnimation {
                duration: 500
            }
            NumberAnimation {
                easing.type: Easing.Linear
                to: 1.0
                duration: 500
            }
            PauseAnimation {
                duration: 500
            }
        }
    }

After performance color of a texture (picture) gradually completely passes in gray, and all is then reverse also it is fulfilled in an infinite loop. Now:

A question actually here in what: and I can change somehow color of any definiteness of a part of a texture (my picture images/image.jpg), i.e. any certain sections. For example I will define in QML two variables xColor, yColor, we transfer it similarly ratio the shader description and then for example the texture will change only in a square with coordinates the left top corner [xColor - 10, yColor - 10] and [xColor + 10, yColor + 10] - bottom right corner. I want:

I know that it can be implemented. How it more optimally to make? In what direction to me to think? Whether there are any similar examples? It would be nice to add blending color (red to gray in this section).


texts: How can I parent an object whilst animating?

texts:
Much like in Blender where you can parent an object to another, or the Armature, is it possible to parent an object to another, so when animating, the child object moves with the parent?

I've tried dropping the object I want influenced onto the character's parent object in the hierarchy and accessed it via the Animation tab. I added the object as a property and adjusted it's position, but the results have been pretty mixed.

How can I have an object automatically follow the animation without manually adjusting its curves for each frame?


texts: How to handle objects at the edges of spatial partition cells?

texts:
A lot of games store object positions as floats and have a closed ball for the game area (eg. a rectangle and objects are allowed to have position coordinates on all 4 edges).

However, this becomes problematic when partitioning the game area (eg. gridding/quadtrees). The edge cases would have to be added in so that 2 edges of the game area are included in rectangles that touch them or objects on 2 edges would have to be missed out in the partition.

Is there another solution to this or do games (and other programs this applies to) usually go with one of the above 2?

(One solution is to use integer coordinates, but what if using floats is unavoidable?)


texts:
I am trying to allow the user to share the final game score on their FaceBook timeline. I am following FaceBook tutorial and examples. When I try to download and import the FaceBook SDK package (7.11-2.0) in Unity (2017.3) I get the error:

  error CD1704: An assembly with the same name 'FaceBook.Unity.Settings' has already been imported. Consider removing one of the references or sign the assembly Library/FacebookSDK/FaceBook.Unity.Settings.dll (Location of the symbol related to previous error)

I read on other posts that the latest version of Unity may have the Facebook SDK already integrated, and will not require importing the package manually.

I therefore removed the from my project. The error disappear, but when I try to initialize the Facebook SDK for Unity using the code below, I get the error:

  The name `FB' does not exist in the current context

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Facebook.Unity;

public class ShareOnFaceBook : MonoBehaviour {

    // Use this for initialization
    void Awake () {

    if (!FB.IsInitialized) {
        // Initialize the Facebook SDK
        FB.Init(InitCallback, OnHideUnity);
    } else {
        // Already initialized, signal an app activation App Event
        FB.ActivateApp();
    }
}


texts: How do I adjust my rigidbody velocity on a local axes?

texts:
I have an fps rigid body script, code listed here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] Camera cam;
    [SerializeField] float camSpeed;

    float yaw;
    Vector3 direction;

    Rigidbody myrigbody;
    void Start()
    {
        myrigbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        cam.transform.Rotate(new Vector3(-Input.GetAxis("Mouse Y") * camSpeed, 0, 0));

        yaw = (yaw + Input.GetAxis("Mouse X") * camSpeed) % 360f;

        direction = new Vector3(Input.GetAxis("Horizontal"), myrigbody.velocity.y, Input.GetAxis("Vertical"));
    }
    private void FixedUpdate()
    {
        myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0));
        myrigbody.velocity = direction;

    }
}

The particular part I'm having trouble with is the last line: myrigbody.velocity = direction;This code is moving my character perfectly, except that it doesn't adjust to my rotation in game.  If i rotate 90 degrees to the right in game, and press forward, I will move to the left (from the players perspective), I will move in the same direction when i press forward (or any other direction) no matter how I have rotated.  How do I alter the rigid bodies velocity while taking into account how the player has rotated?


texts:
I have a rather simple state machine to control my Unity character and as the actions the character can perform increase, so does the complexity of state management, I have been reading about hierarchical state machines, they seem like the answer to my problems but I cannot 'connect' the theory to actual implementation, take for example the below Movement State
public class Player_Movement : BaseState
{
    public Player_Movement(PlayerController playerController, EntityStateMachine_Comp entityStateMachineComponent) : base(playerController, entityStateMachineComponent)
    {

    }

    public override void OnEnter()
    {
        _playerController.GetComponent<Animator>().SetBool("IsMoving", true);
        _playerController.GetComponent<Cast_Component>().OnCastReady.AddListener(() =>
        {
            _stateMachineController.ChangeToState(new Player_Movement_Casting(_playerController, _stateMachineController));
        });
    }

    public override void OnExit()
    {
        _playerController.GetComponent<Animator>().SetBool("IsMoving", false);
    }

    public override void OnFixedUpdate(StateMachineContext _context)
    {
        //If movement input is zero
        if (_playerController.PlayerInput.inputData.Movement.Input == Vector3.zero)
        {
            _stateMachineController.ChangeToState(new Player_Idle_State(_playerController, _stateMachineController));
        }
        else
        {
            _playerController.motor.MoveAndRotateTowards(_playerController.PlayerInput.inputData.Movement.Input_CameraRelative);
        }
    }

    public override void OnUpdate(StateMachineContext _context)
    {
        if (Input.GetKey(KeyCode.LeftShift))
        {
            _playerController.motor.IsSprinting = true;
            _playerController.motor.Speed = _playerController.motor.walkSpeed * _playerController.motor.sprintSpreedModifier;
        }
        else
        {
            _playerController.motor.IsSprinting = false;
            _playerController.motor.Speed = _playerController.motor.walkSpeed;
        }

        if (!_playerController.motor.IsGrounded && _playerController.Rigidbody.velocity.y < 0)
        {
            _stateMachineController.ChangeToState(new Player_Locomotion_Falling_State(_playerController, _stateMachineController));
        }

        if (Input.GetKeyDown(KeyCode.Space) && _playerController.motor.IsGrounded)
        {
            _stateMachineController.ChangeToState(new Player_Locomotion_Jump_State(_playerController, _stateMachineController));
        }
    }
}

My current goal is to have this become my super state for my movement state machine, I would like to add a sub state to this (Cast Movement) that simply calls _playerController.motor.Move instead of _playerController.motor.MoveAndRotateTowards as I would like to have a different style of movement while aiming a spell, but how would I write this substate so that it only handles how the character moves and falls back on the super state for everything else?
I have the feeling I have to re-write how my state machine works but I have no idea where to start except I probably need to seperate transitions out of the states themselves? perhaps? haha


texts: Detecting when object is fully in collider

texts: How to make that when object is fully in collider, just that moment "something happens", now I only know triggering.Hmm I mean when that cube is fully in the collider.


texts:
I want to move a enemy from its current position toward the mouse position in LibGDX.
x, y - enemy position   saveX, saveY - position where my enemy need to go(or mouse position saved at specific time) xSize, ySize - enemy size.

protected Vector2 makeVec(float saveX, float saveY){
    Vector2 v = new Vector2(saveX - x, saveY - y);
    return v.nor();
}

public void update(float dt){
    test += dt;
    dtTime += dt;
    if(cont){
        vec = makeVec(saveX, saveY);
        x += vec.x * speed
        y += vec.y * speed;
        cont = cont();
    }
}

But for some reasons my enemy movement animation is not smooth. What's wrong?


texts: convert image to spritesheet of tiles for isometric map?

texts:
is there a way to convert an isometric image (like the first image) to a spritesheet (like the second image), in order to place each image on the isometric map with the code?

The map looks like the first image, but some buildings are bigger than just one tile, so I need several squares (let's say the first image is a building, made of multiple tiles with different colors), and each square is placed with an offset of 64x32. The building is created in Blender and I save the image with the isometric perspective. But I have to split each square from this image in order to have the spritesheet, maybe there is smarter way, or a java software that would make the conversion for me?


texts:
I want to delimit my speed and to maintain that speed constantly, but it gets getting higher and if i apply the linear velocity it doesnt bounce :/, Here is te part of my code

double fx = .25f*Math.cos(Math.toRadians(rotation));
double fy = .25f*Math.sin(Math.toRadians(rotation));
this.getBody().applyLinearImpulse(World.toGameCoordinates((float)fx, (float)fy), this.bodydef.position);
this.getBody().setLinearVelocity(World.toGameCoordinates((float)fx, (float)fy));

What can i do to maintain the speed constant and it keeps bouncing


texts: What techniques could I use to give players the ability to control certain features, e.g. fatness?

texts:
I'm working on a tool for character customization (e.g. starting from a base model, a player can control his fatness), so I'm looking for ideas, techniques or other regarding this topic.

After some research I thought to this technique: starting from two models (one standard human and one fat human, both with the same data, like vertices and triangles), then creating a new model by storing data about the two original mesh (e.g. store vertex data of the second mesh as color data), and controlling their interpolation with a shader.

What do you think about this idea? Suggestions?


texts: Simple Game Feasibility: Unity + Turbo Squid + $0 =?

texts:
I've been coding 2D games exclusively for a while, partly because I have very limited graphics skills, partly because it takes less effort to make something look great, and partly because I have very limited time in which to code.

I have an idea for a very simple 3d kids game that I'd like to build; it would be based around a player roaming a randomly-generated city and looking for a particular building (eg. dollar store, grocery store, bank, etc.)

My question is: Would it be feasible to build this in Unity, using only free models and animation (presumably from Turbo Squid), in a decent time-frame?

In terms of features, this would range in extremes from "generate some random buildings, paths, and select one as the winning building to locate" to adding people to talk to, objects to interact with (water, ladders, keys and locks, ropes, etc.)

I haven't touched 3D modelling for years (I used 3D Studio Max 3.x back in high school), and I don't have 3-4 hours to spend creating, rigging, and animating models. That's really the crux of my doubt. I also don't have cash that I can spend on models/animation.

So to summarize, my main two questions are:

Is it feasible to create a decent-quality game using free stuff from Turbo Squid?
Are many/most/all of the models from TS compatible with Unity?


texts:
I have picked this puzzle shown here as training in programming games.

  In these mazes you follow the arrows. From each arrow you can move to
  any of the arrows it's pointing to, in the same row, column, or
  diagonal.

More explanation can be found here.

As you can see the Arrow on a yellow background in the top-left corner marks the beginning of the maze. Since this arrow is pointing to the right, the player can move from here to either of the two spaces to the right. The player then chooses which arrow to should move to. If they choose the Down arrow in the top-middle, then for their next move they can travel to any of the spaces in the column below it. If they choose the diagonal arrow, then they can move diagonally.

In short, the arrow direction indicates the path direction the player can move. The player continues making these moves until they arrive at the bulls-eye which marks the end of the maze. Here is a solution to this maze:

What I want is to generate a brand new puzzle each time the player starts the game, so they will have to find a different solution path. The player then makes their choices of moves to solve the puzzle. Then they can generate a new puzzle to solve.

Unfortunately, I'm stuck on this step. How can I generate this kind of puzzle? Do I need some path finding methods and which one will help me to achieve this goal?

I'm using the C# language.

Thanks!


texts: How to FindGameObjectsWithTag then cast the array of GameObjects to an Array of Interfaces

texts:
I have a few GameObjects that implement a common Interface: IsTree.
I need to call the function doTreeThing() on each of those IsTrees after getting a reference to each of them via FindGameObjectsWithTag("tree").

This line complains that it cannot implicitly convert from GameObject[] to IsTree[]

IsTree[] trees = GameObject.FindGameObjectsWithTag("tree");

So then I tried to leave the GameObject[] an iterate over it to convert each individual object inside to an IsTree.

GameObject[] trees = GameObject.FindGameObjectsWithTag("tree");
        foreach (GameObject tree in trees) {
            IsTree isTree = (IsTree)tree;
            isTree.doTreeThing();
        }

But this complains that it also cannot convert GameObject to IsTree.

Then I got a little desperate and tried to make my IsTree into a GameObject.

public class IsTree : GameObject {
    public System.DateTime getAge(){
        return null;
    }
}

GameObject is a sealed type. (I don't really know what that means besides that this does not work)

So how do I get this array of GameObjects into an array of SomeInterface?


texts: Is there a common word that encompasses handling of position, rotation, and scale together?

texts:
I'm looking for a name for my class that manipulates 4x4 matrices that handle position, rotation, and scale. Is there a common word that encompasses all three?

(I'm splitting the matrix math into its own file/class.)


texts: Help me optimize my Line Of Sight on a 2d grid algorithm?

texts:
private bool LOSBetween2Nodes( int2 start , int2 end )
    {
        int2 dif = new int2(
            math.abs( end.x - start.x ) ,
            math.abs( end.y - start.y ) );
        int2 pos = new int2(
            start.x ,
            start.y );
        int2 inc = new int2(
            ( end.x > start.x ) ? 1 : -1 ,
            ( end.y > start.y ) ? 1 : -1 );

        int numIterations = 1 + dif.x + dif.y;
        int error = dif.x - dif.y;
        int walkable = 0;
        bool prevY = false;
        int numSameDir = 0;

        if ( error <= 0 )
            prevY = true;

        dif.x *= 2;
        dif.y *= 2;

        for ( ; numIterations > 0; --numIterations )
        {
            walkable += graphNodeWalkables[ pos.x + pos.y * graphCellLength ];

            if ( numSameDir < 1 )
            {
                if ( prevY )
                    walkable += graphNodeWalkables[ ( pos.x - inc.x ) + pos.y * graphCellLength ];
                else
                    walkable += graphNodeWalkables[ pos.x + ( pos.y - inc.y ) * graphCellLength ];

                if ( error > 0 ) // more steps in x
                {
                    pos.x += inc.x;

                    if ( !prevY )
                        numSameDir++;
                    else
                        numSameDir = 0;

                    prevY = false;
                    error -= dif.y;
                }
                else // more steps in y
                {
                    pos.y += inc.y;

                    if ( prevY )
                        numSameDir++;
                    else
                        numSameDir = 0;

                    prevY = true;
                    error += dif.x;
                }
            }
        }

        return walkable == 0;
    }

This currently checks all grid cells along a line between a certain width and returns telling you if any are unwalkable. This can run thousands-tens of thousands of times a frame.


texts: C++ Text RPG - Commands and their output

texts:
Synopsis

So far i tried to make games and most of the times i finished on having 'engines' ready. Not the games at all. I figured out that after having rendering, music, i/o  handling, all that stuff ready i pretty found myself already burned out and having no idea what the game was about i wanted to write.

And in my at least 10 years of hobby gamedev i completed 10 engines but not a single game.

I got to know OpenGL, GLES, LibSDL and even low level frame buffer rendering - however that knowledge is nothing if you can't get  your game out.

I wrote  my own GL based UI systems, even coded my own scripting language, coded multiplayer tcp/udp client-server game system, coded level editors, model viewers, mesh exporters, ray tracers and tons of shaders. Meantime i worked on other things too - not related to gamedev (like Distributed Computing Libraries, Algotrading stuff, lot of IOT, exploits, machine learning algorithms..) and i finished them all, but still i come back to try to write a game and i fail.

Why?

After so many years i try to answer this question and i think the reason of me not being able to finish a simple game is because i always somehow focused on the engines, core but not the actual game itself.

It's like knowing all about how the game should be running so that you actually see it on your screen with top performance but when you ask me how does these two characters will fight - i would answer - you need to figure it out.

Today

This time is no different. I told myself i will write a game - 'simple' text RPG, no graphics at all - plain text, should be easy - no need to focus on anything but text - easy huh?

No

I just finished to build the scratch of the backend of the game, have the Rooms implemented, Entities, Parsing the input, Json loader, saveing, loading, inventory, commands interpreter and what? Well im stuck.

Problem

Imagine i have the following structure:

CEntity (base class for all entities)
CEntityItem
CEntityDoor
CEntityRoom
CEntityCreature
CEntityCreatureCow
CEntityCreaturePlayer
CEntityCreatureHorse

CCommand (base class for all commands)
CCommandLook
CCommandWalk
CCommandXXXX

The game 'engine' does nothing special, basically it goes endless loop asks for user input, passes the input into command and prints out the return

pseudocode

while(1) {
// Returns a vector of strings, users input split by ' ' space

std::vector<std::string> vCommand = GetInput();

// Go through the available commands and see which fits

for(;;;)
{

         if(m_vCommands[a]->GetCall == vCommand[0])

         printf("%s\n", m_vCommands[a]->Handle(vCommand);
}

}

And when a player types in (example)

Command: look

What i do is just go through the available commands, check which does it fit and pass it as

std::string strOutput = pCommand->Handle(std::vector<std::string>& rvstrCommandArguments);

A proper command object gets called out and performs action - in this example Look, returning a string that is then printed on players screen like:

Output: You look around and find nothing

Other examples of commands i am thinking on top of my head will look like:

fight <name>
craft <empty> - for a list of available options
craft <axe>
hide <where>

Just want to keep it simple to finish it this time.

But here comes the question,

Is it fair to keep the output of the command that should be displayed to the user within the command class itself (just as i do) ?

For now it's simple, but later i will add some text formatting (colors and stuff).

With my OOO approach 'everywhere' sometimes i feel i am overcomplicating things and trying to search for better solutions to problems that do not exist.


texts: Copyright information / issues (if any) for game

texts:
I have always been a fan of the game Heroes of Might and Magic 3 (let's call it simply HOMM3), which shined long ago, around 1998.

For more information, this game was created by the 3DO company - which sadly went bankrupt in 2003. Then in 2015, somehow it was 'revived' (a rendition, actually) as HOM3-HD edition by Ubisoft.

Now, I'm thinking of my own game that uses the theme from this game (well, at least use the game characters and audio for example), which might be published onto Google Play and/or App store.

So I'm wondering: would there be any issues (e.g. risks of being sued, for example by Ubisoft) if I try to use HOMM3 (the original one, as I called it above) art and audio ? For audio, I still own a copy of HOMM3 so I have access to the audio (MP3) files directly from the game folder. For arts, there are spritesheets like this: spriters-resource, which seem to be freely available to use.

These are two versions (owned by 3DO vs owned by Ubisoft), but things could get complicated if we are not prepared, so better be safe than sorry.


texts: Unity C# Object Scaling when parenting by script

texts:
How do I make it so an object doesn't scale with another object that I parented it with by script? If anyone knows how to get around this I would really appreciate it.

This is the part of the script I used for parenting:

arrowToObjAnchor.transform.parent = hitTransform;


texts:
I'm making a racing game that feels a lot like xtreme g 64 or fzero.

Making the player feel like they are moving extremely fast is important for this game. Actually moving them fast enough to give them that feeling is out of the question. Collision detection and a few other aspects of the physics engine prohibit it.

My current solution is the following:

Map the speed to the field of view for the projection matrix so that the FOV is 30 at speed x and 100 at speed y with a linear increase for the FOV inbetween x and y. This will probably be some polynomial once I test it out some.
Trail render any light sources on the vehicle. I am just adding a trail rendered blurred object of the same color as any light source: tail lights, jet flames, etc.
slight camera shake when you are above 3y/2 speed
your max speed without a boost is y/2, when you have a boost the max speed is y and these effects all become pretty noticeable

My Question:
I can't do any post processing effects on the iphone. I'm limited to poor mans solutions like the one I did. Is there another approach that is more common or better? My solution seems like what they would have done back in the N64 days so I'm wondering if there's a better way. The problem with this solution is that it makes it seems cheap to stretch the FOV like I am. It's a cool effect, but still feels cheap when you play it.

Here's a link to a very limited version of my effect

The speed they are simulating is supposed to be 400kph, I'm simulating about 2000 meters per second, about 18 times their speed. so my effects are very exaggerated.

Note:
I'de give you a screenshot but setting up a test scene that doesn't display the art assets would be hard. Setting up one with the art assets would get me sued.
My object is on the ground so I'm avoiding effects that are used more for aircraft.
There is no wind or dust so that is a little more limiting in using those elements.


texts: Building placement in tilemaps (pattern matching)

texts:
I'm building a small RTS and in my code I've given my buildings a pattern, much like you would pieces in tetris, i.e. I want to place irregularly-shaped buildings on a map without overlaps.

The map could be 100x100 and my structure that I'm placing could be as follows:

OXO
XXX
XXX

I'm currently bruteforce-checking each building cell individually against cells in a map.

Is there an easier/nicer way to check a tile map for a matching pattern?


texts:
I'm making a topdown 2.5D game (think the legend of zelda: a link to the past) using libgdx and box2D.

to simulate friction from a topdown perspective, i've set the gravity for the box2D world to 0, and added a friction joint to simulate friction with the floor.
this joint requires 2 bodies, one moving and one stationary and it slows down the moving one simulating friction.
my movable body is a dynamic body (player), and my stationary body (anchor) is a static body that is a sensor (to avoid collisions with bodies)

now I've increased the speed of the playable character, and it feels like he's skating over the ground.
I want to increase the friction, but after I'm not noticing any difference after changing variables.

the variables i've tried changing (that didn't seem to do anything) include:

the .friction on the fixtureDef of either body (player + anchor)
the size of the anchor
the .maxForce of the joint

How do I increase the friction caused by a friction joint in libgdx's box2D implementation?


texts:
I am applying air resistance to a falling sphere using the Euler method. If someone could have a look and tell me if my implementation is correct or offer any tips, it would be highly appreciated.

Calculations taken from http://en.wikipedia.org/wiki/Drag_(physics)

float Mass = 10;
float Radius = 5;
Vector Gravity = Vector(0, 9.8, 0)

float p = 1.293f;              // Air Density;
float A = pow(Radius, 2) * PI; // Cross Section Area;
float Cd = 0.47f;              // Drag Coefficient For Sphere;

float terminalVelocity = sqrt(2 * Mass * Gravity.magnitude / p * A * Cd);

// Update

Vector acceleration = Gravity * ( 1 / Mass);

m_velocity += acceleration * Time.deltaTime;

float drag = 0.5f * p * pow(m_velocity.magnitude, 2f) * Cd * A;

m_velocity -= new Vector3 (0, clamp(drag, 0, terminalVelocity), 0);

m_position += m_velocity * Time.deltaTime;

Cheers


texts: Why it's not adding gaps between the prefabs?

texts:
gap value is 7 but all the prefabs Instantiated at 0,0,0
private void GenerateLines()
    {
        for (int i = 0; i < numberOfLines; i++)
        {
            var prefab = Instantiate(linesPointsPrefab, Vector3.zero, Quaternion.identity);

            prefab.transform.position = new Vector3(prefab.transform.position.x * gap, prefab.transform.position.y * gap, prefab.transform.position.z * gap);
            prefab.transform.parent = linesParent.transform;
        }
    }

After added gaps between the prefabs it's creating lines using linerenderer between the prefabs. then when I drag the prefabs around it's making curved lines and then the NAVI object can move on the curved lines :

It was working before too but I wanted to generate the curved lines automatic.
So with the gaps I can drag the prefabs around and make curved lines and next I will add automatic random positions option too so it will make the curved lines already.


texts: How to restrict an AssetReference to a specific type?

texts:
I am using the Addressables package of Unity.

I am trying to restrict an AssetReference type in the Unity inspector to a specific type.  Currently a user can assign any Unity object to an AssetReference, but I would like to guide the user to assign the correct types to the correct variables and (if possible) filter the assets type list to include only the assignable types when the user click on the drop-down arrow

According to the Unity documentation https://docs.unity3d.com/Packages/com.unity.addressables@1.6/api/UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute.html

it seems like there is some sort of annotation available. The documentation is very limited and I have tried:

[UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute(type=typeof(PlayerMaster))]
public UnityEngine.AddressableAssets.AssetReference playerMaster;

but it made no difference.

I also tried to create my own AssetReference type:

    [Serializable]
    public class Reference : UnityEngine.AddressableAssets.AssetReferenceT<PlayerMaster>, UnityEngine.AddressableAssets.IKeyEvaluator
    {
        public Reference(string guid) : base(guid)
        {
        }
    }

but with this new type I cannot select anything!

The following code snippet at least seems to restrict the list to GameObjects which is an improvement, but the user can still assign the wrong GameObjects easily. I was hoping for a more strict filter, but if it is not possible I will settle with:

public UnityEngine.AddressableAssets.AssetReferenceGameObject playerMaster;


texts: Game engine: a decent way, architecture-wise, to implement scripting support?

texts:
I am developing a simple game engine (in C#, if it matters), and I can't think of a decent enough way to implement scripting in terms of architecture.

It's a simple turn-based strategy with custom, logic-independent animations for battles. It has a global architecture layer for system/low-level stuff and, most importantly, two main modules - logic and game-view thingy - that communicate using an event manager.

And the thing is, I would really like to have the scripts influence both stuff related to the game logic (changing unit parameters, etc) and stuff related to the game-view, such as special animations/dialogues for battles that might depend on a certain scripted trigger.

(To be honest, ideally I want the script to control the game flow, leaving only the core mechanics/graphics to the logic/view, but I'm new to this, so I'm not sure I can do it right now)

I've been thinking of three options:

Just let the scripting live in the logic, but let it know about the graphical side of the game. But this would make the logic/view division very vague, won't it...
Make the scripting a separate module that will exchange events with the others using the same event manager. But this would require to be very careful about event synchronization, I guess... and also add a whopping lot of event types to the manager. (Still, personal favorite)
Make the scripting a module above all, so it can directly influence/call functions of the logic/view. This allows for an inherently wider functionality at the cost of sort of screwing the entire event exchange scheme and being afraid that the script can break stuff even when it really shouldn't.

So, I can neither decide on one of these nor think of a better way to insert the scripting module... Any suggestions or useful links?

Thank you!

P.s. thanks for migrating the question, didn't know there was a specialized section for gamedev


texts:
So I'm pretty happy with my terrain, and the progress on my game. I just want to figure out why the terrain is so steep sometimes. Right now to generate my random seed I use this:

seed = (long)(Math.random() * 10000000 + 12345670);

It works, but some of the seeds just make a really steep point hill, while I'm looking for more bumpy-flat maps (similar to Terraria's).

Here's my create terrain loop:

for (int i = minX; i < maxX; i++) {
    int columnHeight = p.getNoise(i, maxY);
    for (int j = 0; j < columnHeight; j++) {
        System.out.println(columnHeight);
        map[i][j] = new Tile(i * 8, j * 8, 8, 8, TileType.Grass);
    }
}

Here's the class I'm using to try to generate terrain. I tried tweaking parameters but nothing works, and I just keep getting crazy random hills.

public class Perlin {
    private long seed;

    // Constructor to create a seed
    public Perlin(long seed){
        this.seed = seed;
    }

    // Fetches a random value
    private int random(int x, int range){
        return (int) ((x + seed) * (x + seed) * 8) % range;
        // o = (int) (((x + seed)*(x + seed))*5) % range
        //return o;
    }

    // Calculates the noise
    public int getNoise(int x, int range){
        int chunkSize = 64;

        int chunkIndex = x  / chunkSize;

        float prog = (x % chunkSize) / (chunkSize * 1f);

        float left_random = random(chunkIndex, range);
        float right_random = random(chunkIndex + 1, range);

        float noise = (1 - prog) * left_random + prog * right_random;

        return Math.round(noise);
    }
}

Here's a picture of the terrain compared to what I want (what I want is in red):

EDIT
So I understand what you guys mean about the previous Perlin class not actually being perlin noise. I fixed it with some tweaking and using actual perlin noise, the only thing I'm partially confused about is the seeds, and how do they work..

for example in Java this is how they do it

x = (x<<13) ^ x;
return (float)( 1.0 - (( (x * (x * x * 1376312589 + 789221) + 1376312589) + 3517) & Integer.MAX_VALUE) / 2543768824f);

if someone could explain what all that really means it'd be great, and why does it use prime numbers?


texts: What does it take to get an ESRB rating for my game?


texts: What exactly makes up a screen in a typical C64 game?

texts:
I'm trying to figure out the basics of C64 game development past BASIC, and I could use some advice on something very basic, but important: What is all that stuff on the screen actually, and how to draw it?

Take a look at Katakis/Denaris:

There are at least 9 different things on the screen:

The Score bar, with different fonts
The ship itself
A satellite attached to the ship, detachable
Secondary Weapon Projectiles
Primary Weapon Projectiles
Moving objects (can be enemy ships)
The Status bar, featuring an image of the ship, the number of lives and three sections that can fill
The primary weapon charge bar, can fill to the end
A scrolling starfield in the background
(not numbered on the screen) Solid objects like rocks or metal walls that are part of the background

The C64 only supports 8 sprites per horizontal scan line, so I don't think that everything in the middle of the screen can be a sprite? I would assume that anything requiring a collision would be a sprite (since I can get hardware collision detection with sprites), but even then I quickly hit the limit of 8 sprites. Also, my weapons can fire much more than one projectile - my ship, the satellite and 6 bullets would already be 8 sprites on a row (look at about 50 seconds into the video).

Also, which graphics mode would a game like this use? The Programming Handbook lists Bit Map Mode which essentially modifies screen memory directly. Is this the mode I should usually be working in? How would I compose all the non-sprite elements together to get them on screen?

A lot of the stuff in the score and status bar is static ("Area: 01" or the "frame"), so I guess I'll just populate them once when the level starts. Things that need updating - the score, the charge bars at the bottom - would be updated by filling the screen memory with black and then drawing the new score every frame?

Or do I have to draw the entire screen on every frame?


texts: Chess engine stock fish process for mobile

texts:
I am making the chess interface I designed for a game. I am using the process to get answers from a stock fish binary:

stockfish = new Process {
                StartInfo = new ProcessStartInfo {
                    FileName = System.IO.Directory.GetCurrentDirectory () + "\\Assets\\Scripts\\Stockfish\\stockfish.exe",
                    Arguments = "",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardInput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }

            };

The problem I face is it worked for my Windows build but for mobile package build it won't work with the executable. Is there a way around it?


texts: How can I implement an Iris Wipe effect?

texts:
For those who doesn't know:

  An iris wipe is a wipe that takes the shape of a growing or shrinking
  circle. It has been frequently used in animated short subjects, such
  as those in the Looney Tunes and Merrie Melodies cartoon series, to
  signify the end of a story. When used in this manner, the iris wipe
  may be centered around a certain focal point and may be used as a
  device for a "parting shot" joke, a fourth wall-breaching wink by a
  character, or other purposes.

Example from flasheff.com

Your answer may or may not include a coding sample, a language agnostic explanation is considered enough.


texts: How do i get the drawing to loop automatically with out need for user input scrolling?

texts:
#include <iostream>
#include <time.h>
#include <iomanip>
#include <SDL.h>
#include <stdlib.h>
#include <string.h>
#include "screen.h"
#include "Stars.h"
#include "Allstars.h"

int main(int argc, char* argv[]) {

    //seeding random number generator

    srand(time(NULL));

    //------------------------------------------------------------------------------
    /***CREATING SDL WINDOW***/
    /***CREATING RENDERER & TEXTURE***/
    /***CREATING A BUFFER***/

    Screen screen1;
    screen1.init();

    //-----------------------------------------------------------------------------
    /***GAME LOOP***/

    /*UPDATING buffer with texture information*/

    Allstars allstars1;

    while (true) {
        int num=0;
        screen1.screenClear();
        allstars1.updateStarPosition();

        // Allstars class to retrieve  m_pstars from the Allstars class into the main function.

        const Stars * const pStars = allstars1.getStars();

        for (int i = 0; i < allstars1.NSTARS; i++) {
            Stars star = pStars[i];

            // here is where i tried to loop each star back to the bottom of the screen  when they reached the top of the screen.

            if(num>3 && star.m_y_star<-0.97 && star.m_y_star>-1){

                    star.m_y_star=0.99;
                    star.m_x_star= star.m_x_star;

                }

//each star is given a random location by giving co-ordinates: m_x_star & m_y_star a random value using a function in Stars.h
// You can't get negative co-ordinates on the screen so we map from [-1,1] to [0 to SCREEN_WIDTH and 0 to SCREEN_HEIGHT]

            int x = (star.m_x_star + 1) * ((Screen::SCREEN_WIDTH) / 2);
            int y = (star.m_y_star + 1) * ((Screen::SCREEN_HEIGHT) / 2);
            screen1.setPixel(x, y, 128, 0, 255);
        }

        /*UPDATED USED TO UPDATE TEXTURE and RENDERER and PRESENT DRAWING ON SCREEN*/
        screen1.update();

        /* Check for messages and events
         */

        //Quitting SDL through clicking 'x' button event
        if (screen1.processEvents() == false) {
            break;

        }
        num++;
    }
    //-----------------------------------------------------------------------------
    /***FREEING MEMORY & QUITTING SDL***/
    screen1.close();
    return 0;
}
//------------------------------END OF MAIN----------------------------------------

I tried to get use a for loop to change the vertical position of the star once it draws close to the top of the window but that doesn't seem to influence the program. Stars (purple dots) seem to drift off the screen and don't appear from the bottom of the screen again. No errors occur and i have incorporated checks to prevent the stars being plotted off of the screen. Can someone help me make these purple dots loop infinitely without the need for scrolling.


texts: Why are entities in a component system composed at run time?

texts:
Why are entity component systems the way they are? For example as far as I have seen it may look like this

class Entity
    list of components
    add component
    remove component
    update comentent
    ....

So you are building your entities at runtime. I assume it will look like this

 Entity ork;
 ork.add(AI).add(movement).add(physics).add(renderer)

The problem I see with this approach is that errors appear at run time instead of compile time. It also seems to add a lot of potential errors for example the AI system only makes sense if the entity also has a movement component.

What is the advantage of building your objects that way instead of doing it like this?

class Ork: IEntity
     movementComp
     AiComp
     physicsComp
     rendererComp
     ....
     //wire everything together

One possible advantage that I can see is that object creation takes less code because you don't really need to wire up your objects, you just add your components and your done.

Would you please enlighten me?


texts: Method for creating a next gen MMORPG out of thin air?

texts:
Update August 2012: thank you all for your answers. I started small as suggested, creating first a Facebook Game about it, the next step will be to port it later on PC for a 3D version, and much later as a MMORPG as I would have build credibility and funding. The upcoming FB game will be done by Blup Blup Game Studio (my studio). Thanks.

Original Question:
Background:
I am documenting since a few months a game design document (GDD)(sci-fi & fantasy MMORPG) all by myself, without any real game design background (I am just a Chartered Accountant (CA and CISA)). For now, it looks more like a proposal document.

The question:
If you would have a series of amazing ideas that would revolutionized MMORPGaming how would you create that company out of thin air? Focus on creating the initial core team that would create the mockup that would be present to capital venture companies for major financing.

You may not be financial expert here but you did a massive amount of games in the past, of various types and platforms. With our different backgrounds we are complementary.

Cheers,

Raistx

P.-S. Edited for a leaner question. Removed elements linked to money as it's not the core question. I know how to get money and convince cap venture CIES, but I need a mockup / high pitch to do so.


texts:
DISCLAIMER: So I asked this on StackOverflow and was told it was not a good question for the community but was suggested to check here. If this question sucks or just doesn't belong here either, feel free to let me know. It seems a fair question to me, but I know it's important to maintain high standards on these sites.

So I just put the finishing touches on a poker game in JavaFX. Part of the functionality in this program is a single player mode, where you can play hands against the computer. To be transparent, this is a university project, so I'm not aiming for perfection. More, just an ai that behaves semi-intelligently for game variation and minor challenge for casuals.

So to be clear, I am aware of general poker strategy, and have found numerous articles/research papers/links on more in-depth poker AI's designed to compete against competitive players. I guess as an analogy, there's the Easy mode bots in League of Legends, then there's the deep learning AI that beat a DOTA pro in laning.

I'm definitely aiming for the former here. While I currently have a basic algorithm that works as:

if(gamestate = flush, straight, 3-pair, full-house, face card pairs)
{
     raise 1/4 pot;
}
else if(gamestate = pair, potential flush or straight, etc)
{
     check/call;
}
else
{
    fold;
}

So I already have functionality that can detect current board/hand states, but I do not have any functionality that can estimate chances at winning the hand, compare with opponent's possible hands, etc. Since the game only needs to be for casual play, the more advance algorithm's seem like massively overkill.

I guess my wishful thinking hope is that something exists similar to min-max in tic tac toe, although poker is obviously more complex. But something that can make some kind of rough approximation of hand value, that wouldn't require thousand's of if statements to cover every possible situation.

So if anyone knows of any algorithms that would be used in, for example, a poker phone game or such, I'd really appreciate some help. To reiterate, if this question is too vague, I'm happy to provide any other information about my existing research, program design, or anything in this vein.


texts: Applying angular velocity distorts model

texts:
I am calculating the orientation of a sphere through the following code

wV = new Vector3(0, pi/2, 0);
w = new Quaternion(wV, 0);
// o is the current Orientation
o.Normalize();
w = 0.5f * w * o;
// dt is the elapsed time since the last frame
o += w * dt;

However it seems that over time the sphere tends to become distorted and then shrink back to its original size. Is this due to the simplicity of the integration or am I doing some simple mistake?


texts: GLSL blur shader algorithm results in a lumpy blur?

texts:
I'm writing a Gaussian blur shader and it's coming along pretty well. However, when I run it on a circle, the result is lumpy.

I'm using a simple nested for loop to create the blur. Here's the code in it's current form:

int samples = 10;
int sampledist = 1;
float rt_h = 720; // render target height
float rt_w = 1280; // render target height

vec4 effect(vec4 col, Image tex, vec2 texcoord, vec2 screencoord)
{
   vec3 final = vec3(1.0, 0.0, 0.0);
   final = Texel(tex, texcoord.xy).rgb;
   for (int i=-samples; i<samples; i++)
   {
      for (int j=-samples; j<samples; j++)
      {
         final += Texel(tex, texcoord.xy + vec2(i*sampledist, j*sampledist)/vec2(rt_w, rt_h)).rgb * .01;
      }
    }
    return vec4(final, 1.0);
}

(Note: I'm using a variation of the regular GLSL language for Love2D, so the above code isn't completely valid GLSL shader code)

What is wrong with my algorithm?


texts:
In my game, I have a player, ennemies and tiles like Mario. And each entity has a different behavior when it touches a tile. For exemple, when my player walks on spike he dies. But a certain type of ennemy can walk on spike without dying.

Is there a good way to write this interaction between objets in OOP. I mean without cast, without breaking OCP principle and not having to write every behavior in every objects. Is there a design pattern for this purpose ?


texts: Why do actors stretch when I add them to a stage in LibGDX?

texts:
I have started learning LibGDX and I have been making a few little games to learn how it all works but ever since I started using stages and actors, all of my textures stretch horizontally and I can't seem to fix it at

public class GameScreen extends BaseScreen
{
private BaseActor background;
private PhysicsActor spaceship;
private BaseActor rocketfire;

private PhysicsActor baseLaser;
private AnimatedActor baseExplosion;

private ArrayList<PhysicsActor> laserList;
private ArrayList<PhysicsActor> rockList;
private ArrayList<BaseActor> removeList;

public GameScreen(BaseGame g)
{
    super(g);
}

public void create()
{
    spaceship = new PhysicsActor();
    Texture shipTex = new Texture("fire.png");
    shipTex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    spaceship.storeAnimation("default", shipTex);
    spaceship.setPosition(400, 300);
    spaceship.setOriginCenter();
    spaceship.setMaxSpeed(200);
    spaceship.setDeceleration(20);
    spaceship.setEllipseBoundary();
    mainStage.addActor(spaceship);
}

public void update(float dt)
{

}
}

BaseScreen class

public abstract class BaseScreen implements Screen, InputProcessor
{
protected BaseGame game;
protected Stage mainStage;
protected Stage uiStage;
public final int viewWidth;
public final int viewHeight;
private boolean paused;

public BaseScreen(BaseGame g)
{
    this(g, 1024, 600);
}

public BaseScreen(BaseGame g, int viewWidth, int viewHeight)
{
    game = g;
    this.viewWidth = viewWidth;
    this.viewHeight = viewHeight;
    mainStage = new Stage(new FitViewport(viewHeight, viewHeight));
    uiStage = new Stage(new FitViewport(viewWidth, viewHeight));
    paused = false;
    InputMultiplexer im = new InputMultiplexer(this, uiStage, mainStage);
    Gdx.input.setInputProcessor(im);
    create();
}

public abstract void create();
public abstract void update(float dt);

public void render(float dt)
{
    uiStage.act(dt);
    if (!isPaused())
    {
        mainStage.act(dt);
        update(dt);
    }

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    mainStage.draw();
    uiStage.draw();
}

I changed the texture to a perfect red square but when renderered on the screen it was more rectangle shaped than square (horizontally) and I have no idea why. I read somewhere that it was something to do with the camera but I have no idea what to do to fix it! Please help :O


texts: Java game design question (graphical objects)

texts:
I'm beginner in game development, in Java and here on this site too and I have a game design question. Please comment my idea:

I have a main loop which call update and draw method. I want to use an ArrayList which stores graphical objects, they have coordinate and image or text to draw and my game objects extends this class. In update, I can choose which objects should be put in the array and in draw method I'll display the elements of array on the screen. I'm using a buffer and draw first there.  Here is a simple (not full) code, only the logic:

public class GamePanel extends JPanel implements KeyListener
{
   ArrayList<graphicalObjects> graphArray = new ArrayList<graphicalObjects>();

   public void update()
   {
      //change the game scene, update the graphArray, process input etc.
   }

   public void draw()
   {
      //draws every element of graphArray to a JPanel
   }

   public static main(String[] args)
   {
      while(true)
      {
          update();
          draw();
      }
   }
}

My questions:

Should have I use interface or abstract class for graphicalObjects? graphicalObjects class and the ArrayList really needs or there is some better solution?
How to draw objects? They draw themself with their own method or in the draw method I have to draw manually based on graphicalObjects variables (x,y coordinates, image etc.)?
If this conception is wrong, please suggest another one!


texts:
I'm doing shadow maps, and my shadows move around, "shimmer", when I move around the camera. It is difficult to spot on still images but very much noticable in motion.

I read an MSDN article describing the very same problem - http://msdn.microsoft.com/en-us/library/windows/desktop/ee416324(v=vs.85).aspx - but even with their fix, the problem still very much persists - in fact, I hardly see any difference at all.

Here's how I construct view/projection for my directional light source, and the measures I take to combat "shimmering" yet which does not work - why?

Mat4 CreateDirLightVPMatrix(const Vec3& lightDirection, const Mat4& viewProjectionMatrix, const float shadowMapResolution)
{
    const Vec3 lightDir = glm::normalize(lightDirection);
    const Vec3 perpVec1 = glm::normalize(glm::cross(lightDir, Vec3(0.0f, 0.0f, 1.0f)));
    const Vec3 perpVec2 = glm::normalize(glm::cross(lightDir, perpVec1));

    Mat4 rotationMatrix(Vec4(perpVec1, 0.0f), Vec4(perpVec2, 0.0f), Vec4(lightDir, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f));

    Vec4 corners[8] = { Vec4(-1.0f, -1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, -1.0f, 1.0f),
                        Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, -1.0f, -1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, -1.0f, 1.0f) };
    const Mat4 inverseVPMatrix = glm::inverse(viewProjectionMatrix);
    for (uint32_t i = 0; i < 8; i++)
    {
        corners[i] = inverseVPMatrix * corners[i];
        corners[i] /= corners[i].w;
        corners[i] = corners[i] * rotationMatrix;
    }

    float minX = corners[0].x, minY = corners[0].y, minZ = corners[0].z, maxX = corners[0].x, maxY = corners[0].y, maxZ = corners[0].z;
    for (uint32_t i = 0; i < 8; i++)
    {
        if (corners[i].x < minX)
            minX = corners[i].x;
        if (corners[i].x > maxX)
            maxX = corners[i].x;
        if (corners[i].y < minY)
            minY = corners[i].y;
        if (corners[i].y > maxY)
            maxY = corners[i].y;
        if (corners[i].z < minZ)
            minZ = corners[i].z;
        if (corners[i].z > maxZ)
            maxZ = corners[i].z;
    }

    Mat4 viewMatrix(rotationMatrix);
    viewMatrix[3][0] = -(minX + maxX) * 0.5f;
    viewMatrix[3][1] = -(minY + maxY) * 0.5f;
    viewMatrix[3][2] = -(minZ + maxZ) * 0.5f;
    viewMatrix[0][3] = 0.0f;
    viewMatrix[1][3] = 0.0f;
    viewMatrix[2][3] = 0.0f;
    viewMatrix[3][3] = 1.0f;

    Vec3 halfExtents((maxX - minX) * 0.5, (maxY - minY) * 0.5, (maxZ - minZ) * 0.5);
    // supposed fix from MSDN article - does not have any effect at all
    float texelSize = 1.0f / shadowMapResolution;
    halfExtents.x /= texelSize;
    halfExtents.y /= texelSize;
    halfExtents = glm::floor(halfExtents);
    halfExtents.x *= texelSize;
    halfExtents.y *= texelSize;

    return glm::ortho(-halfExtents.x, halfExtents.x, -halfExtents.y, halfExtents.y, halfExtents.z, -halfExtents.y) * viewMatrix;
}


texts:
From http://docs.unity3d.com/ScriptReference/BuildPipeline.BuildAssetBundle.html, I am using the sample code

using UnityEngine;
using UnityEditor;
public class ExportAssetBundles {
    [MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]
    static void ExportResource () {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {
            // Build the resource file from the active selection.
            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
                                           BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
            Selection.objects = selection;
        }
    }
    [MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]
    static void ExportResourceNoTrack () {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {
            // Build the resource file from the active selection.
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
        }
    }
}

To build an AssetBundle. However, whenever I run this on a prefab, I noticed that Unity switches the platform to WebPlayer and THEN builds the bundle. But I need the AssetBundle to be built for iOS and Android - I don't need WebPlayer bundles.

Why does it keep switching to WebPlayer platform whenever I run this? How can I build for iOS and Android?

My prefab is just an object with a Sprite Renderer.


texts: I have installed direct SDK and I have visual studio 2010 , I started to write code and compile and when I run I get error of unresolved external symbols or some sort of this , I searched and I found that I need a library called legacy_stdio_definition.lib which I don't have in my files , note my code worked on other computer that have vs 2010


texts: How to access and change a Tilemap's Order in Layer?

texts:
I'm making a game about two ghosts, and an important thing that I want to add is the possibility to pass through walls. I have managed to make the passable behaviour and everything.
Next, I need to change the Tilemap's Order in Layer number. That's because I want to add some things inside the Tilemap that should be shown until player passes the wall. The way I though of to do this is to decrease the tilemap's layer order when the player is inside it, and put it back to the previous value when player exits.


texts: How do I draw 2D sprites from a sprite sheet in DirectX 11 without ghosting/artifacts

texts:
I'm new to DirectX and I am trying to get my feet wet by making a simple 2D game. I chose DirectX 11 and am using the DirectX ToolKit helper library which recommended I start with DX11 and not DX12.

The guide I am following to create an animating sprite is working great except for when attempting to draw a single sprite from the sprite sheet I am seeing "ghosting" of other sprites behind it. I created the sprite sheet and saved it as a PNG and also as a BMP and it seems to happen either way.

Here is the sprite sheet I am using:

It is 336px width, 48px height, in 48px x 48px square sprites. If I render the entire sprite sheet, or if I render the first sprite (0,0,48,48), it looks fine, but if I attempt to render the 2nd, 3rd, 4th, etc. this is how it renders:

Here is the code I am using to load the PNG file as a texture:

ComPtr<ID3D11Resource> ponyIdleResource;

DX::ThrowIfFailed(
    CreateWICTextureFromFile(_D3dDevice.Get(), L"assets/pony_idle.png",
        ponyIdleResource.GetAddressOf(),
        _Texture.ReleaseAndGetAddressOf())
);

ComPtr<ID3D11Texture2D> ponyIdleTexture;
DX::ThrowIfFailed(ponyIdleResource.As(&ponyIdleTexture));

CD3D11_TEXTURE2D_DESC ponyIdleDesc;
ponyIdleTexture->GetDesc(&ponyIdleDesc);

and here is the code I am using to draw:

_SpriteBatch->Begin();

RECT sourceRect;
sourceRect.left = 48;
sourceRect.top = 0;
sourceRect.right = 96;
sourceRect.bottom = 48;

_SpriteBatch->Draw(_Texture.Get(), _ScreenPos, &sourceRect, Colors::White, 0, _Origin);

_SpriteBatch->End();

If I pass the RECT in as 0,0,48,48, it looks fine. Is there some special way I need to format my image? I've tried it as both PNG and BMP.


texts:
So, everything was clear from the specification point of view, but when I moved to reading through some of the original implementations and reimplementations, I ran into this:

f = ldexp(1.0,rgbe[3]-(int)(128+8));

This piece calculates the signed exponent (<128 are, by specification, defined to be negative) and applies it to 2.0f. Why does he add 8 after the fact? And why doesn't he just write 136? That's biasing the encoded exponent information in favor of the smaller values, right? But why? All the values I load with this seem to be in a really cramped floating point space [I'm not even sure anything uses the space above 1.0f]. I understand the ratios remain consistent, but I kind of prefer to rely on original measured radiances.

http://www.graphics.cornell.edu/~bjw/rgbe.html — The code here states that is the standard way to decode "real pixels", which has no basis in the specification and no rationale offered.


texts: All scripts in Unity game can not be loaded

texts:
I can not provide a "why" here, because as far as I can tell it happened spontaneously - after saving an edit to one of my scripts, it just started happening. But here's the problem:

Every single one of my scripts, while still in the same Scripts file, can no longer be found and loaded. All the Script Components (take the Game Manager component for example) now look like this:

or like this:

Attempting to locate the scripts by going Add Component > Scripts > [Desired Script] doesn't work, because there isn't even a Scripts item in the Add Component menu. I have already looked this up, and none of the answers I found were applicable:

Yes, every script's file name is the same as the Class name within them
I have tried reimporting all  assets (Assets > Reimport All), no success.
Taking all scripts out of the project, restarting unity and then reimporting the scripts. Nothing
Removing all script components, then reapplying them. It didn't work because, as I said, there was no Script item in the Components menu.

This is a pretty game-breaking, literally, because this is a hobby game (I'm not doing this as a job, it's just in spare time). If I can't restore the game as it was, I won't be able to bring myself to restart it. So any help is greatly appreciated.


texts: Unity3D - Upload a image from PC memory to WebGL app

texts:
I need user to upload his(her) avatar picture from PC to game

How can I create a file dialog and upload a image to WebGL game?


texts: Use IPointerEnterHandler with bool function?

texts:
Im trying to use mouse pointer to detect any UI element on my canvas. when pointer enter any UI element, UI_active set true, else UI_active set false. Here is my script:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;// Required when using Event data.

public class UI_AVATAR : MonoBehaviour, IPointerEnterHandler {

public bool  UI_active;

public void OnPointerEnter(PointerEventData eventData)
{
    Debug.Log("The cursor entered the selectable UI element.");
    print(eventData.currentInputModule.name);
    print(eventData.pointerCurrentRaycast.gameObject.name);

}

}


texts:
I made a script which swaps two game objects on click.But the script won't work because the objects are actualy clones of the original prefab.

This is the script (UnityScript):

#pragma strict

var object1 : GameObject;
var object2 : GameObject;
function OnMouseDown ()
{

Instantiate(object2,object1.transform.position,object1.transform.rotation);

Destroy(object1);
}

I use this script to create other game objects (clones)[c#] :

using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {

public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 2f;

// Use this for initialization
void Start () {
    Spawn ();
}

void Spawn()
{
    Instantiate(obj[Random.Range(0, obj.GetLength(0))],transform.position, Quaternion.identity);
                    Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
                    }

}

The objects get renamed to NAME (Clone).

What I wanna do is make the script affect clones too.So they will swap when I click on them.


texts: Set Parent to Instantiated Objects in Unity

texts:
i am having problem in attaching parent to the instantiated objects. I have attached the code below. please tell me where i am doing wrong. Thank you.

public GameObject brick;
public Transform BrickHolder;
//public GameObject Bricks;

void Start(){
    for (float y = 2.16f; y < 4.88f; y += 0.34f){
        for (float x = -2.125f; x <= 2.125f; x += 0.85f){

            GameObject Bricks = Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity) as GameObject;

            if (Bricks != null) {
                Debug.Log("Hello");
                Bricks.transform.SetParent(BrickHolder);
            }

        }
    }
}


texts:
I was thinking about peer-to-peer games by considering a simple coin tossing game.

  You open up your version of P2PCoinFlipping Beta 2.3 and it displays a
  list of player name servers. After choosing the closest server a
  scoreboard of the luckiest players appears. You choose the highest
  ranking player and the game begins. Since you started the battle the opposing player
  chooses the coin side, heads, and you are assigned tails.
  A nice little graphic appears displaying a tumbling coin eventually landing on heads.
  Too bad, you lose.

But how do you know the outcome is fair?

If the outcome is chosen on your computer you can edit the program to choose to win and the same applies to the opponent. The game isn't deterministic so you can't seem to validate the outcome.

Is it possible to have multiple independent adversarial agents agree on a non deterministic event?


texts: How can a make a game end and display win message when the mouse/figure is placed/clicked on a certain tile?

texts:
I am trying to make a game, kind of like Minesweeper, but instead of looking for mines, you are looking for a 'hidden base' that is hidden under one of the unturned tiles. I am new to this and have no idea how to make it happen. I want when the mouse double-clicks on the 'hidden base' tile the game to display "You win!" message (I got the message ready, just need to put it in.) and the game to end.
I tried with '''while(isGameRunning){...}''', the made a  boolean class isGameOver, but I can't seem to be able to target the tile. BTW. Each tile is placed randomly across the board each time a new game starts.


texts: Why doesn't RGB565 lead to a smaller memory footprint on Android?

texts:
I'm using LibGDX for my game. I'm loading 9 bitmaps into memory at once using the AssetManager, about 512x512 pixels each on average.

TextureParameter texParam = new TextureParameter();
texParam.format = Format.RGBA8888;

assetManager.load("islands/island_0.png", Texture.class, texParam);
assetManager.load("islands/island_1.png", Texture.class, texParam);
assetManager.load("islands/island_2.png", Texture.class, texParam);
assetManager.load("islands/island_3.png", Texture.class, texParam);
assetManager.load("islands/island_4.png", Texture.class, texParam);
assetManager.load("islands/island_5.png", Texture.class, texParam);
assetManager.load("islands/island_6.png", Texture.class, texParam);
assetManager.load("islands/island_7.png", Texture.class, texParam);
assetManager.load("islands/island_8.png", Texture.class, texParam);

However, if I switch the format to Format.RGB565, then run the Heap allocation tracker in the DDMS view of Eclipse, I see absolutely no change in the memory allocated. The bitmaps being drawn on the screen though are being rendered differently (without an alpha channel when I use RGB565).

Am I missing something? Why aren't the bitmaps using less memory?


texts:
I'm using a gaussian blur fragment shader.  In it, I thought it would be concise to include 2 subroutines: one for selecting the horizontal texture coordinate offsets, and another for the vertical texture coordinate offsets.  This way, I just have one gaussian blur shader to manage.

Here is the code for my shader.  The {{NAME}} bits are template placeholders that I substitute in at shader compile time:

#version 420

subroutine vec2 sample_coord_type(int i);
subroutine uniform sample_coord_type sample_coord;

in vec2 texcoord;
out vec3 color;

uniform sampler2D tex;
uniform int texture_size;

const float offsets[{{NUM_SAMPLES}}] = float[]({{SAMPLE_OFFSETS}});
const float weights[{{NUM_SAMPLES}}] = float[]({{SAMPLE_WEIGHTS}});

subroutine(sample_coord_type) vec2 vertical_coord(int i) {
    return vec2(0.0, offsets[i] / texture_size);
}

subroutine(sample_coord_type) vec2 horizontal_coord(int i) {
    //return vec2(offsets[i] / texture_size, 0.0);
    return vec2(0.0, 0.0); // just for testing if this subroutine gets used
}

void main(void) {
    color = vec3(0.0);

    for (int i=0; i<{{NUM_SAMPLES}}; i++) {
        color += texture(tex, texcoord + sample_coord(i)).rgb * weights[i];
        color += texture(tex, texcoord - sample_coord(i)).rgb * weights[i];
    }
}

Here is my code for selecting the subroutine:

blur_program->start();
blur_program->set_subroutine("sample_coord", "vertical_coord", GL_FRAGMENT_SHADER);
blur_program->set_int("texture_size", width);
blur_program->set_texture("tex", *deferred_output);
blur_program->draw(); // draws a quad for the fragment shader to run on

and:

void ShaderProgram::set_subroutine(constr name, constr routine, GLenum target) {
    GLuint routine_index = glGetSubroutineIndex(id, target, routine.c_str());
    GLuint uniform_index = glGetSubroutineUniformLocation(id, target, name.c_str());
    glUniformSubroutinesuiv(target, 1, &routine_index);

    // debugging
    int num_subs;
    glGetActiveSubroutineUniformiv(id, target, uniform_index, GL_NUM_COMPATIBLE_SUBROUTINES, &num_subs);
    std::cout << uniform_index << " " << routine_index << " " << num_subs << "\n";
}

I've checked for errors, and there are none.  When I pass in vertical_coord as the routine to use, my scene is blurred vertically, as it should be.  The routine_index variable is also 1 (which is weird, because vertical_coord subroutine is the first listed in the shader code...but no matter, maybe the compiler is switching things around)

However, when I pass in horizontal_coord, my scene is STILL blurred vertically, even though the value of routine_index is 0, suggesting that a different subroutine is being used.  Yet the horizontal_coord subroutine explicitly does not blur.

What's more is, whichever subroutine comes first in the shader, is the subroutine that the shader uses permanently.  Right now, vertical_coord comes first, so the shader blurs vertically always.  If I put horizontal_coord first, the scene is unblurred, as expected, but then I cannot select the vertical_coord subroutine! :)

Also, the value of num_subs is 2, suggesting that there are 2 subroutines compatible with my sample_coord subroutine uniform.

Just to re-iterate, all of my return values are fine, and there are no glGetError() errors happening.

Any ideas?