texts: How can I rotate the cube left and right?

texts:
I want to rotate a cube left and right with that:

using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    private Vector3 offset;
    public GameObject player;
    public GameObject center;
    public GameObject Left;
    public GameObject Right;
    public int step = 9;
    bool input = true;
    public float speed = 0.01f;

    void Update()
    {
        if(input == true)
        {
            if (Input.GetKey("a"))
            {
                StartCoroutine("moveLeft");
                input = false;
            }        }
        if (input == true)
        {
            if (Input.GetKey("d"))
            {
                StartCoroutine("moveRight");
                input = false;
            }
        }
    }

    IEnumerator moveLeft()
    {
        for(int i = 0; i < (90/step); i++)
        {
            player.transform.RotateAround(Left.transform.position, Vector3.forward, step);
            yield return new WaitForSeconds(speed);
        }
        center.transform.position = player.transform.position;
        input = true;
    }

    IEnumerator moveRight()
    {
        for (int i = 0; i < (90 / step); i++)
        {
            player.transform.RotateAround(Right.transform.position, Vector3.back, step);
            yield return new WaitForSeconds(speed);

        }
        center.transform.position = player.transform.position;

        input = true;
    }
}

and the problem is when I press a and d cube move left or right but + 0.5 up.

I also have tried this update method, but now it turns only on the y rotation axis:

public float rotationSpeed = 10f;
public GameObject player;

void Update()
{
    if(Input.GetAxis("Horizontal") < 0)
    {
        player.transform.Rotate(
            0,
            Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime,
            0);
    }

    if (Input.GetAxis("Horizontal") > 0)
    {
        player.transform.Rotate(
            0,
            Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime,
            0);
    }
}


texts: Get all triangles that are < N dist from you?

texts:
Does anyone know of a way I could add a radius to this code for p? Like basically saying "this is true if the triangle is < N dist from the point"

public boolean isPointInTriangle( Vector3f p, Vector3f a, Vector3f b, Vector3f c )
{
    return ( pointsAreOnSameSide(p, a, b, c) && pointsAreOnSameSide(p, b, a, c) && pointsAreOnSameSide(p, c, a, b) );
}

public boolean pointsAreOnSameSide( Vector3f p1, Vector3f p2, Vector3f a, Vector3f b )
{
    Vector3f diffba = new Vector3f(0,0,0);
    Vector3f.sub( b, a, diffba );
    Vector3f diffp1a = new Vector3f(0,0,0);
    Vector3f.sub( p1, a, diffp1a );
    Vector3f diffp2a = new Vector3f(0,0,0);
    Vector3f.sub( p2, a, diffp2a );

    Vector3f cross1 = Vector3f.cross(diffba, diffp1a);
    Vector3f cross2 = Vector3f.cross(diffba, diffp2a);

    return ( Vector3f.dot( cross1, cross2 ) >= 0 );
}


texts: How do I cheaply place a watermark over what's rendered in OpenGL 3.0+?

texts:
I would like some insight about how to place an image with an alpha, and a certain amount of opacity, on the top of everything that is rendered. What's the cheapest way to do that?

I use C++ with a programmable OpenGL pipeline.


texts: Make a triangular mesh from of a map defined by points that follow the coast lines

texts:
I have a set of points which follow the coast lines of a world map.  I would like to triangulate it so that I can render the continents filled in.  The points seem to be in order so that if you render as lines, the only issue is when a land mass starts and ends you get lines you shouldn't have between them.

Does anyone know of a good way to go about making a triangular mesh out of this data?


texts: Light propagation through sub-step ray tracer

texts:
I have this crazy idea.

What if you made a real-time 3D render that for each frame, progressed some number of light bouncing. In effect this is a ray tracer but it does the ray tracing in steps. First step is direct lightning, second step is 1 degree of indirect lightning and third is 2 degrees of indirect lightning.

For each step, you would accumulate the information in a new frame buffer. Obviously there are limitations to this because you are only considering what's on screen but is the idea sound? Can it be done? What does it look like?

I'm eager to try it out because it appears simple but I'm wondering if something like this doesn't already exist.

Basically a ray tracer implemented with real-time 3D rasterization that converges over time (with sub steps, more than 1 pass per frame) this convergence can be adjusted.


texts: what is the simplest way to get player selection system like checkers in unity 3d c#

texts:
like lets say the board is a top down grid like if your were in front of an actual checkers board i want to figure out how i would be able to select/deselect a piece then select/deselect a space on the board so that the players piece will move to said place and if another piece is occupying that place already then the said player cant move there

also im new to c# and progrming in general...i have been only doing it for about five months and have been looking at tutorials and all that ... but if some one could paste an example code if possible something simple so that i can dissect it, learn from it, and change it as I see fit.

and if you can explain how the code works that would be really appreciated.

things i need:
some kind of grid/checker board code
player selection/deselection

i would prefer it in c# and the code applicable strictly to unity3ds mono develop although I intend to learn visual studio in the future at the moment i just want something for unity.

lastly please assume that i may be stupid when explaining/writing your example code/ or answer.


texts: Which Design Patterns Should I consider for Quest Management?

texts:
I am working on an fantasy RPG and I would like to get some ideas about how I am implementing Quests.

Quests in my game are very generic. The quest goal can be almost anything in the game. The goal can be: press a GUI button; pick up a certain object; kill a creature; steal an object; collect 10 items; walk to a certain location; etc. Therefor, quests need to be somehow tied to many other objects in my game.

I've been flirting with the Observer design pattern, but I'm not sure if this is the best approach.

Currently, my Quest Manager singleton is an observer, and it registers itself with many subjects. For example, I have a menu class with GUI buttons that has an EventHandler, and the Quest Manager registers with the menu class to have its own function called when a certain button is pressed. When the function gets called, the Quest Manager checks to see if the "Press the button" quest is in progress, and if it is, then that Quest becomes "Completed"!

Is this a good design or are there other design patterns that I should consider?


texts:
As most of you know, embedded interpreters for languages like Lua and Python are widely used for scripting game logic, but I haven't seen much information on people going with domain-specific languages for their scripts, e.g. building a little logic scripting 'dialect' on top of the language used for the rest of the game, using macros or fluent programming or whatnot.

So my questions are as follows:

What examples of such DSLs have you seen in real-world games?
What problems were run into?
Would you recommend this route for other game developers, and in what circumstances?
Do you see this becoming more common as game development moves toward more metaprogramming-friendly languages, e.g. Boo?


texts: OpenGL are strips/fans faster for rendering or just data bandwidth

texts:
When we send data for drawing we can mark it as TRIANGLE_STRIP or TRIANGLE_FAN to reduce the number of vertices we have to specify. Now, does this actually improve the rendering speed on the graphics card, or does it merely reduce the amount of data that has to be sent to the card?

I'm using a very simple model. To construct it correctly I need multiple calls to glDrawArrays using TRIANGLE_STRIP. If I switch to using just GL_TRIANGLES I could have just one call to glDrawArrays. Is this type of apporach useful, or is the overhead of an the call to glDrawArrays low enouhg that it won't make a difference.

I will profile, but since I have only one card I don't know if my result will be indicative of the general case. (NOTE: I need to be ES2 compliant, so some of my options are limited).


texts: Running a C# Function in Unity with a button press

texts:
Heads up - I'm not very experienced with Unity, and haven't coded in C# before. (I have some experience in Python)

I'm trying to create an app that requires small packets to be sent from a smartphone to a Raspberry Pi.  In order to do this, I'm using OSC - or Open Sound Control.  I have the Raspberry Pi setup to listen for messages, just having trouble with Unity.

I'm using UnityOSC (there's two of them)
Github: https://github.com/thomasfredericks/UnityOSC
Documentation: http://thomasfredericks.github.io/UnityOSC/

I'm trying to send a packet of data whenever a button is pressed (and each button needs to send a different packet to identify which button has been pressed).  I don't know how I can create a script that is activated with a button press.

Is there a way to make one script with a function that takes the button name as a parameter and then send that?

Thanks for the help, and if you need more information, please ask!  Again - I don't have experience with this and I would appreciate a "lower experience level" explination.  Thanks!


texts: Tilemap is sent to back/disappears behind background when I go into play mode or save (video included)

texts:
screencap of the problem here
I'm sure this has a simple solution but I haven't found it answered yet. I have two tilemaps, one a BG and one a middle layer, and everything works when I paint on the middle layer. It shows up on top of the BG.
But if I save the project or open play mode to test it, the middle layer disappears. Seems like it gets sent behind the BG tilemap but the order of the tilemaps hasn't changed. Also of note is that nothing changes even if I reorder the tilemaps, and the only way I can make the tilemap "reappear" is by ctrl-z undoing my last action. At a loss, any takers?
EDIT: I just realized that my video capture didn't pick up my drop down menus, but I create a new tilemap at the bottom of the hierarchy, put some assets in it, then save the project (stuff disappears) and then undo (stuff reappears).


texts:
I know how to check collision for example 2 spheres. But my question is how do I use the collsion response in a good way?

How do I make my character unable to walk in to the Sphere? I've got to the point where my game send a PrintLn when isCollided and it works but my character just walk through it.

How should I do?

Cheers!


texts:
Most Outline Shaders or Tutorials found online, are Shaders which are sharp edge-outlines.  Like here:

Even though a lot of games are already using soft outlines
 like here:

with a nice gradienty- blurry effect.

Creating a Outline is basically easy (as described here: http://wiki.unity3d.com/index.php/Silhouette-Outlined_Diffuse)

Also ive seen that wanted effect in 2D:
https://www.assetstore.unity3d.com/en/#!/content/84126

But how do they do it in 3D?

Ive found a useful step-by-step guide here: (https://willweissman.wordpress.com/tutorials/shaders/unity-shaderlab-object-outlines/) . But the first step is already not working. (rendering the 3d object in as pure white to a rendertexture).


texts: MagicaVoxel - Making it look exactly the same in Unity

texts:
Am playing around with MagicaVoxel, then exporting as an obj, and importing into Unity.

What I am trying to do is make it appear exactly the same in Unity as it does in MagicaVoxel, but am not sure how.  I've played with the lighting, a few different shaders, but nothing comes close to how it looks in MagicaVoxel.

Below is a screen shot of Unity and MagicaVoxel so you can see the difference.  The colors in Unity just seem so dull.  Looking at the sand in MagicaVoxel compared to Unity is so much brighter.  I know that there is AO in MagicaVoxel, but for now I'm just trying to get the colors to be correct.

The object is using the standard shader (Unity 5.3), with the albedo set to an image...

In the Unity screen shot, it's using a basic directional light (default settings in screen shot).

Any advice?


texts: How do I animate pieces between puzzle states?

texts:
I'm developing a simple C# puzzle game as a learning exercise, using OpenTK. It's similar to Puzzles and Dragons' puzzle part: The aim is to match 3 pieces to remove them. Removed pieces are replaced.

I have the puzzle part done such that matches are deleted and more pieces are added from the top. How can I animate tiles dropping from the top after rows/columns have been deleted? (You can see this happening about 4~5 seconds into the video on the website linked above.)

My idea was to create an "imaginary" board above the actual board so when tiles are deleted, I would in essence lower the imaginary board down, moving it further down on each frame. This brute force approach sounds like it could be done more easily with some APIs, but I've not had any luck with this.

Is there a better way to do these animations?


texts:
I am intending to build a circular menu, with menu items equally distributed around the circle. When clicking on a menu item the circle should rotate so that the selected item is facing the top. I am using libgdx and I am not very familiar with the Actors concept, so I intuitively  tried to implement an Actor, who is drawing a texture and then transforming it by using Actions, with no success:

    class CircleActor extends Actor {

    @Override
    public void draw(SpriteBatch batch, float parentAlpha) {
        batch.draw(texture1, 100, 100);
    }

    @Override
    public Actor hit(float x, float y) {
        return this;
    }

}

and the rotate action:

    CircleActor circleActor = new CircleActor();
    circleActor.action(Forever.$(RotateBy.$(0.1f, 0.1f)));
    // stage.addActor();
    stage.addActor(circleActor);

The texture is rectangular, but it doe not work. 1. What is wrong? 2. Is it a good approach to solve the task?


texts: Remove "dots" noise (like from dot-matrix printer)

texts:
I have 2D array of floats. Using the floats, I generate image by doing proportional selection of color from between COLOR_MIN, COLOR_MAX – for maximal float value at given (x,y), I choose COLOR_MAX and put pixel at (x,y), for minimum float value – I choose COLOR_MIN.

Resulting 128x128 image (created from 128x128 float array) is then used as texture, which is then scaled to about 500x500 size. Image displayed this way has "dot-noise", like if the image would be printed from needle printer (example image/screenshot attached below).

How to avoid the noise? I could scale the image myself to 512x512, but I probably need some filtering? Or will be setting some OpenGL (ES) options for the texture sufficient?

PS.: The image is result of GL_LINEAR magnifying filter. Using GL_NEAREST results in large pixels being clearly visible (green below). So apparently, I need programmatic filter to run on CPU.


texts: Game Maker: is 08 the same as 8 in arrays?

texts:
if I make an array A_[01], can I refer to it later with A_[1]?

I am asking because I am not sure if this is the reason why I am getting some bugs.


texts: How do I deal with floating-point error given a far-away camera?

texts:
Whenever a camera is "far" away (its location is some "large" vector), trouble arises when rendering objects close to it: It is the classic precision loss from subtracting 2 floating point numbers.

I know these ways around it:

using doubles for projection/viewing transformations (may not be feasible/possible on mobile devices),
doing the subtraction on the CPU (with doubles or integers) and uploading the (relative) position of the object into the shader. This position vector is then added to the vector, that is to be transformed in the vertex shader,
tweaking the camera view matrix or model matrix. These matrices are then combined on the CPU and uploaded.

How do these methods compare? Have I missed some other approach?


texts: Making the player fall below the actual map

texts:
I have a 2d map of integers

0000000000
0200000001
1111100011

0 = sky/empty
1 = ground
2 = player

When player falls in a hole/cliff I want the player to go below the map, so it will look like the player had died by falling in the hole/cliff.

Here is what I did:

if(player.getY()+player.getHeight() > map.getHeight()){
   //player has fallen in hole/clifff
}

The code above will test if the player's feet touch the end of map. But how to move him below the map?
Because if I move the player down then the array will be out of bounds.

Is there way without changing the map array?


texts: Costs for developing an Iphone physics game?

texts:
I recently made a game demo inspired by a wooden board game where you drop the ball trying to make a score, is fully playable so take a look (Works best on firefox):
https://dl.dropbox.com/u/62131673/LuckyBall-Chrome/index.html

I want to build this game for the Iphone's App Store, add accelerometer features, menus, unlockable levels, best scores, etc. I'm a graphic designer so I prefer to keep working on the presentation (graphics, assets, sound, music) and leave the rest to the programmer.

I want to know how much this game would cost for a programmer to be developed, so I can make a video at kickstarter.com and sell the idea, with luck this game will see the light.

I don't want to open a debate on the subject, I just need advice on the costs so I can hire someone.


texts: How to make Unity 2D game fit all mobile screen resolutions?

texts:
I have to manually change the camera orthographic size and game sprites etc for each resolution to fit properly. I'm looking for a simpler way to adjust the game to any mobile resolution without retyping and readjusting code for each mobile screen resolution.
This is a mobile 1080x2160 portrait view using a camera orthographic size of 5. The issue is that the paint drops to the far left and right are off screen and the cup does not fully reach to the left or right of the screen unless the resolution is less than 1080p

This is the same size but the camera orthographic size is 6. Even though the paint drops fits the phone resolution the cup still does not fully reach to the left or right of the screen.

This is 720x1280 with the camera orthographic size of 6. The paint drops do not reach to the left and right side of the screen because the view is zoomed out. The cup also wont fully reach to the left and right side.


texts:
I have an RTS game with a camera that can be controlled by either edge-pan, gamepad analog stick or keyboard buttons (WASD). The speed and snappiness are good for the general case, but sometimes feels to slow when going to far-away places on the map.
What's a good algorithm to implement some form of acceleration on the camera without making it feel less snappy? Preferably, this algorithm should work best for the analog stick, since mouse+keyboard can easily use the minimap to navigate as well.


texts: I added the fix of adding this line "Dorg.lwjgl.opengl.Display.allowSoftwareOpenGL=true" to vm arguments, updated my drivers but nothing is working......my error message still remain same has shown in the image


texts: What language do you program in Lumberyard?

texts: I've looked through the FAQ on amazons site and all they mention is C++/Lua for the web service stuff. Can i assume it's C++ for the game content itself or something else (the visual script editor doesn't count)?


texts: Controlling a GameObject from another GameObject's script component

texts:
I'm creating a game where when starting the game, a Cube is duplicated GridSize * GridSize times when the game starts. Now, after the cubes are duplicated I want to attach a variable to them, say "Flag" which is a bool, from another script component (let's say I have a Prefab that generates the cloned cubes).

In short, I have something like this:

CreateTiles.cs : Attached to Prefab

void Start() {
    createMyTiles(); // a function that clones the tiles
    flagRandomTiles(); // a function that (what I'm trying to do) "Flags" 10 random cubes
}

CubeBehavior.cs : Attached to each Cube

public bool hasFlag;
// other stuff

Now, I want flagRandomTiles() to set a Cube's hasFlag property via code, assuming I have access to them via a GameObject[] array.

Here's what I've tried:

Cubes[x].hasFlag = true; - No access.
Making a function such as Cubes[x].setHasFlag(true) - still no access.
Initializing Cubes as a CubeBehavior object array, then doing the above - GameObjects can't be converted to CubeBehaviors - I get this error when I try to assign the Cubes into the array.

How do I do this?


texts:
I have problems with my PhysicsWorld in Andengine GLES20. Sometimes when i first load my app and level there is no velocity added to my bodies. they also rotate slower as it seems. This also happens in Game when I press the home button and then go back into the app.
Any ideas? Is this fixed in the AnchorCenter Branch?


texts: Can I get around a Pokemon copyright with new art and minor changes?

texts:
If I develop a game that is essentially pretty much Pokemon (you're a trainer, you catch "monsters" and put them to fight and level up etc), and I do the next things:

I'm a trainer with a 6-"Monsters" party.
Mechanics like the PC, Gym Leaders and "tall grass" will be used.
I will throw an "ball" to catch the weakened "monster".
I will use common item names, like "potion", "high potion".
The battles are almost the same as Pokemon in terms of mechanics (four moves, elements, critical, evasion etc)
I will NOT use Pokemon names nor graphics... artwork is mine.
Some of the attack names will match Pokemon attack names. I think it is okay, like "ember". Come on.

With all these points, I shouldn't run into copyright issues or anything right? Even if the game feels a lot like Pokemon itself?


texts:
I want to generate a world like minecraft's with an algorithm that treats every block separately. I want the world generator to be a single large function that takes in the x,y,z coordinates and returns what block should be placed in that spot.

It should work without knowledge of what the adjacent blocks are. It should be able to generate terrain with biomes, trees, caves, ore deposits and structures like villages.

Is it possible to make such a world generator and if so, can I get some pointers to how it can be done and what topics to research? If somebody wrote a tutorial about doing that it would be perfect. I hope this isn't a duplicate question because I am specifically interested in generating each block completely independent from its surroundings.


texts:
How does one create a fullscreen window properly in OS X from the code, instead of just expanding into the current desktop?

I am referring to the sort of fullscreen window that one gets when the top-left-most green button is pressed.

Is this actually possible?


texts: What tools are available for developing 2D games like Tetris or Angry Birds for Android?

texts:
I would like to ask the following regarding developing Tetris- and Angry Birds-like 2D games for Android:

Is Java the official development language for Android?
What free or commercial Android development environments (like Xcode is for iOS) are available?
What open source game development engines, like cocos2D, are available for Android?
Are there any great tutorials available for developing such games?


texts: Spritekit - gradually apply force vector in different direction (space ship turning)

texts:
I have a space ship that I'm applying a force vector to using a joystick for control.  I would like this to smoothly fly around when I'm switching directions..  Exactly like minisquadron if you've ever played that..

Let's say I move the joystick to the far right and apply a force on the physics body of (1,0)  and then I abruptly switch directions without circling the joystick around and apply a force of (-1,0).  The ship will move to the right and then slowly lose speed before switching in a linear fashion.

What I want is for it to slowly transition between those two vectors so that it flies in a tight circle.

I'm trying to figure out the best way to write this.. maybe using a loop..  but I could use some help.

pseudo code:

func joystickMoved(){
    let point = pointVector;
    self.moveShip(pointVector);
}

func moveShip(pointVector: pointVector){

    // get current angle
    let curAngle = self.ship.physicsBody.velocity.toAngle()

    // get joystick angle
    let newAngle = pointVector.toAngle

    // while there is a sizeable difference in angles..
    // this loop needs to occur with some delay
    // so transition doesnt occur too quickly
    while fabsf(newAngle - curAngle) > 0.5 {

        // make tiny transitions towards newAngle.. this needs more detail
        curAngle += 1
        let newVelocity = CGPoint(cos(curAngle), sin(curAngle))
        self.ship.physicsBody.velocity = CGVector(dx: newVelocity.x, dy: newVelocity.y)

    }
}


texts: Selection with region (when rendering with shaders and VAO)

texts:
I am currently render my geometry using "Modern OpenGL" approach (with shaders and buffers). I have already implemented picking of single primitives using glReadPixels. Now I am faced with problem how to implement selection of multiple objects. I cannot use glReadPixels because maximum (and it seems meaningful for me) number of objects that I could select with 10x10 box is 100. But it is really necessary for my purposes to have ability to select thousands of objects in small selection area.

I already read answer to similar question where was recommended to test each point against selection rectangle. But it gives new problems: all my vertices are already stored in buffers and it looks like huge performance to test each point on CPU.

Could someone help with such issue?


texts: Creating runtime mesh colliders for roads in Unreal Engine 4

texts:
I want to create several mesh colliders in game at runtime. By mesh colliders I mean "complex collision".

The meshes are for curved roads. The roads will be rendered using hierarchichal instanced static mesh, the visible road meshes will be high poly detailed meshes. For collision purpose I will create simple low poly meshes at runtime and I want collision checks for them.

I also want these meshes to be stored in single actor for easy handling.

Is there any existing class or plugin that does this, or a way to implement it myself? I have checked procedural mesh component and runtime mesh component but they don't seem to have what I want.


texts: Who kept a blog for a year with a new game idea every day, and where is it?

texts:
There's this indie game developer who tried to come up with a new original idea for a game every day for a year - and he put all his thoughts on his website. +200 ideas so far, if I remember correctly.

I don't remember the URL to his site, or the name of the author. Anyone know what I'm talking about?

[Delete this post if it doesn't belong here! Just wanted to add it to the blog thread if I managed to find it]


texts: Do I need to copyright my game before releasing it on the Android Play store?

texts: I am developing a game on Android and I was wondering if I have to copyright it before putting it on the store (so no one can steal the idea)?


texts: Deciding Which Platforms to Support -- Silveright (+Android?)

texts:
My "usual" stack for game dev is to create (in-browser) Silverlight games. I've decided I want to branch into iPhone or Android, and decided to go droid because it's cheaper (considering I don't have a Mac).

Having now all the requisite software and hardware, how do I decide which games to code on both platforms and which to not?

In an ideal world, it would only cost me 5-10% more (time/effort) to port it to Android having developed it for SL. But I know the worst case is 100%+ (i.e. rewrite), and that it'll be somewhere in the middle.

Considering everything will likely be free (although it might be worth it to release the SL one free and offer a $5 paid one on Android, not sure), what are factors to look at?


texts:
The game I've been working on uses opengl/sfml for graphics. I'm currently working on the interface and I've found determining all the proper offsets/positioning etc. to be a pain. To make it configurable, I'll likely end up parsing a making a bunch of xml files to parse that tell my program what images to use/where to position them stc. for the interface.

Since I'm going to need to do that anyways, I was curious if it's possible to embed an html renderer into an app, and have it display over graphics drawn in opengl? That way i could theoretically use html pages to design the interface

If it is possible, how difficult would it be and is it a good idea? are there any projects that do this already?

Thanks


texts: Obscuring stored info in a flat-text file

texts:
I have an idea for an addon for World of Warcraft which would basically be a minigame within the game itself. Eventually, I'd like to have players be able to compete against each other directly. The game would have some RPG-like elements, particularly statistics and abilities, which it would be undesirable for the end users to modify.

So the fact that this is a client-side script, where everything (logic and data storage) are all in flat text files, means that it's impossible for me to truly secure things. But I'd like to at least make it non-trivial to alter things, e.g. so that you can't just open up a file in notepad and type in 'Strength = 256'.

I'm looking for any ideas on how I might obfuscate the data, preferably something which is easy to implement as it's not really what I feel like spending my time on, but probably more sophisticated than ROT-13.

As an example, one idea I had, which I'm not sure if it's feasible (have never made an addon for WoW before) is to serialize the data in base-64.


texts:
How to move Stage?

I am looking for an example:

stage.draw(x,y); // ???

Thanks you


texts: Moving an image by rotating and increasing y axis causes a trailing issue

texts:
Forgive me if me anything is unclear, this is a tricky thing for me to explain.

In an applet I draw a little ship gif. I have it so I can rotate the object and then increase or decrease the y axis to move the little guy around the screen. The problem it seems is that the coordinates for the ship are not in sync with those of the applet window?

For example: the boundaries for my applet window are 800 by 600. I move the ship by rotating it and then increasing or decreasing the y axis, but whenever the Y axis is exceeds 600 or is lower than 0 I get this weird trailing issue. Am I doing buffering right?

here are my "Main" and "ship" classes:

Main class:

    public class Main extends Applet implements Runnable, KeyListener
{
    ship player1;
    private Image i;
    private Graphics buffer;
    AffineTransform affineTransform = new AffineTransform();

    public void init()
    {
        this.setSize(800, 600);
        this.setBackground(Color.BLACK);
        addKeyListener(this);
    }

    @Override
    public void start() {
        player1 = new ship();
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void paint (Graphics g){
        Graphics2D g2d=(Graphics2D)g;
        player1.paint(g2d, this);
    }

    @Override
    public void update(Graphics g){
        Graphics2D g2d=(Graphics2D)g;
        if(i == null){
            i = createImage(this.getSize().width, this.getSize().height);
            buffer = i.getGraphics();
        }
        buffer.setColor(getBackground());
        buffer.fillRect(0, 0, this.getWidth(), this.getHeight());
        buffer.setColor(getForeground());
        paint(buffer);
        g2d.drawImage(i, 0, 0, this);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()){
        case KeyEvent.VK_RIGHT:
            player1.rotateRight();
            break;
        case KeyEvent.VK_LEFT:
            player1.rotateLeft();
            break;
        case KeyEvent.VK_UP:
            player1.moveUp();
            break;
        case KeyEvent.VK_DOWN:
            player1.moveDown(this);
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void run() {
        while(true){
            repaint();
            try {
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

ship class:

    public class ship {
    private Image sprite_ship;
    //private Image ship_engines_green;
    private int x = 300;
    private int y = 500;
    //private int dx = 10;
    private int dy = 10;
    private int my = 0;
    AffineTransform affineTransform = new AffineTransform();
    double rotation;

    public ship() {
        sprite_ship = Toolkit.getDefaultToolkit().getImage("ship.gif");
        //ship_engines_green = Toolkit.getDefaultToolkit().getImage("ship_engines_green.gif");
    }

    public void moveDown(Main M){
        y += dy;
        System.out.println("Y axis: "+y);
        System.out.println("X axis: "+x);
    }

public void moveUp(){
        y -= dy;
        System.out.println("Y axis: "+y);
        System.out.println("X axis: "+x);
    }

public void rotateRight(){
    rotation += 5;
    System.out.println("Rotation : "+rotation);
}
public void rotateLeft(){
    rotation -= 5;
    System.out.println("Rotation : "+rotation);
}
    public void paint(Graphics g, Main M){
        int spriteHeight = sprite_ship.getHeight(null);
        int spriteWidth = sprite_ship.getWidth(null);
        Graphics2D g2d=(Graphics2D)g;
        affineTransform = g2d.getTransform();
        g2d.rotate(Math.toRadians(rotation), x+spriteWidth/2, y+spriteHeight/2);
        g2d.drawImage(sprite_ship,x,y,M);
        rotation = 0;
    }
}

much thanks for any suggestions or if anyone can point out something I'm doing that's terribly misguided.


texts: Texture Packer - Any way to make it combine intelligently

texts:
I am making a Pokemon Clone, using libgdx. I have the different types of sprites: e.g. Back, front, back shiny, and front shiny.

The current way the Texture Packer combines the textures seems to be semi-randomly. I would like to be able to tell it to put the sprites together based on number, because my sprites go:

003
003b
003bs
003s

Where the 003 is the pokedex number, and the b is for back, and s for shiny.

Two questions here:

Is there a way to get it to sort the textures in some way?
Is there a benefit to this sorting?


texts: Do I need to obtain a license to use real car brands in a game?

texts:
We are small team which working on car racing game but we don't know about licensing process for branded cars like Nissan, Lamborghini, Chevrolet and etc.

Do we need to buy any licence for using real car brand names, models, logos,... or we can use them for free?

Second option we think about using not real brand with real models is it possible?
If someone have experience with that, fell free to share it.
Any information about that is welcome.


texts:
I want to implement deformation of plastic material, like plasticine for example. Where should I start to study? What technique should I use?

Thank you for any advice.

EDIT

I want to use it in real-time in kind of a 3D game, not a physics simulation. When I "push" on the plasticine, it is expected to spill. I want to rotate it or any other actions.

Look at this video: http://www.youtube.com/watch?v=mDbVHEg5qC4


texts: Techniques for (literally) cutting corners on square grid maps

texts:
My game involves a level with deformable terrain and units that can travel in any direction but are slowed down by uneven terrain. Normal A-star should work fine in most cases, except on flat land where no matter how the general purpose pathfinder worked it would not send units on a direct path. Theta-star would work if the entire level was fairly flat, but would be much slower if it initially had to take uneven terrain into account.

I think a Manhattan-distance base A-star algorithm would be fast and give a good enough hint to allow other path finding or steering algorithms to take over, but I'm not sure what type of algorithm to use to look ahead and decide when to abandon the path, take a more direct route, and where to jump back on the path later.

(Theta-star seems like it would be too inefficient if it was adjusted to take things like slopes, obstacles, or roads into account. See the solution proposed to the comment about avoiding minefields at: http://aigamedev.com/open/tutorials/theta-star-any-angle-paths/ )

Edit: I did not mention that I already implemented and tested A-star on a similar grid. (I think I accidentally deleted something in this question.) Some of the more obvious cost/heuristic functions I considered just don't result in realistic paths on a grid when an obstacle blocks the most direct path (basically when path-finding is useful) (example pictures). The change to the cost function used by the Theta-star algorithm seems like an ideal solution (considering the constraint of using a grid), but it makes the assumption that tiles have the same travel costs (and it takes much longer).

My original reasoning behind using Manhattan distance was to outsource the "corner cutting" algorithm from the path-finding algorithm, since it was more important to have a fast path-finding algorithm in case the obstacle layout or terrain changed. It makes more sense to do the "corner cutting" algorithm once when the unit arrives than on every permutation of every search of path-finding algorithm (the results of which may end up being scrapped anyway.) A four-neighbor search with Manhattan distance is also interesting because you can see boxes of alternate paths and identify right triangles formed by the original path and the shortest path.

A better question would have been "What is a fast way to identify shortcuts in a path with 90 degree turns?"


texts: GameMaker - Sprite will not stop moving backwards

texts:
I am very new to game development, and I am using GameMaker Studio as my first engine. I was following along with a tutorial to create an Asteroids-like game from scratch, but right now I am trying to create my own coding. There are small problems, but I believe it may just be my coding. The coding language is GML, its proprietary language.

The first problem is that I cannot get my sprite to stop moving backwards:

motion_add(image_angle,-0.2);
if (speed < 0) speed = 0;

It seems okay, since I am trying to force the sprite to have a motion of zero if the speed starts going negative.

Another thing is that I cannot seem to get the bullets to fire from my ship. The code is under the event "Press <Space>":

bullet = instance_create(x,y,obj_bullet);
bullet.speed = 15;
bullet.direction = image_angle;

The bullet literally just doesn't appear, at all. I know it isn't invisible because firing at an asteroid will not destroy the asteroid.

Thanks for the help everyone!


texts: Objects spawned on clients only appear locally

texts:
I'm trying out the new Unity 5.1 networking for a Bomberman style game and i can't seem to get the bombs to instantiate on both the client and all those connected, what am i missing?

The code below instantiates a prefab at the players current position, that prefab has a Network Identity and a Network Transform same as the players, i thought if the object is spawned using "NetworkServer.Spawned(Object)" then that would be instantiated on both clients?

    // Update is called once per frame
void Update()
{
    if (isLocalPlayer)
    {
        this.transform.Translate(new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0.0f));

        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject item = Instantiate(prefab, this.transform.position, Quaternion.identity) as GameObject;
            NetworkServer.Spawn(item);
        }
    }
}


texts: Unity ScrollRect many objects perfomance issue

texts:
I have scrollrect setup and over 1000 objects to scroll through. Currently i'm Instantiating all the 1000 objects at once and notice fps drop. I'm using 2d mask and disbale pixel perfect. Both gave a perfomance boost, but i still Think the bottleneck is that i have 1000 objects already created on the scene. Instead create what is visible to the eye.

What can i do? I've looked into pools. But i dont know how i should use it in my case. Since the inventory is dynamic.

public void ShowInventory(PlayerObject player)
{
    for (int i = 0; i < inventory.GetContainerSize; i++)
    {
        Item item = inventory.GetContainer[i];
        Button itemButton = Instantiate(buttonPrefab, content);
        itemButton.GetComponent<InventorySlot>().SetInventorySlot(player, item, item.amount);
    }
}


texts:
I am having issues with the camera, I cant find how to invert the AXIS

Now

A point is 0,0,0
B point is 1,0,0
C point is 0,0,1

What I want is

A point    0,0,0
B point    0,0,1
C point    1,0,0

I cant find the way to do this, so if you can explain also why is this happening it will be great! (if you need more code ask for it)

Code:

final float eyeX = 2.0f;
    final float eyeY = 10f;
    final float eyeZ = 6.0f;

    final float lookX = 1.0f;
    final float lookY = 0.0f;
    final float lookZ = 6.0f;

    final float upX = 1.0f;
    final float upY = 0.0f;
    final float upZ = 0.0f;

    Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

ViewPort

    GLES20.glViewport(0, 0, width, height);

    final float ratio = (float) width / height;
    final float left = -ratio;
    final float right = ratio;
    final float bottom = -1.0f;
    final float top = 1.0f;
    final float near = 1.0f;
    final float far = 25.0f;
    Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);


texts: How can I draw gizmos and move the drawn gizmos when moving the transform in the editor in scene view?

texts:
public void OnDrawGizmos() {
        if(_thisT == null) _thisT = transform;
            if(!Application.isPlaying && _posBuffer != _thisT.position+_startPosOffset){
                _posBuffer = _thisT.position+_startPosOffset;

            }
            if(_positionSphereDepth == -1){
                    _positionSphereDepth = _positionSphere;
                }
                if(_spawnSphereDepth == -1){
                    _spawnSphereDepth = _spawnSphere;
                }
            Gizmos.color = Color.blue;
            Gizmos.DrawWireCube (_posBuffer, new Vector3(_spawnSphere*2, _spawnSphereHeight*2 ,_spawnSphereDepth*2));
            Gizmos.color = Color.cyan;
            Gizmos.DrawWireCube (_thisT.position, new Vector3((_positionSphere*2)+_spawnSphere*2, (_positionSphereHeight*2)+_spawnSphereHeight*2 ,(_positionSphereDepth*2)+_spawnSphereDepth*2));
        }

_posBuffer is Vector3
_spawnSphereDepth is float

The problem is that it's drawing the cube in the center of the scene view window and when I'm changing the transform position the cube Gizmo is not moving.

Is there a way to draw the DrawWireCube so it will be position around the transform and when moving the transform that the gizmos draws will move with it too ?


texts: Subdividing a polygon into boxes of varying size

texts:
I would like to be pointed to information / resources for creating algorithms like the one illustrated on this blog, which is a subdivision of a polygon (in my case a voronoi cell) into several boxes of varying size:

http://procworld.blogspot.nl/2011/07/city-lots.html

In the comments a paper by among others the author of the blog can be found, however the only formula listed is about candidate location suitability:

http://www.groenewegen.de/delft/thesis-final/ProceduralCityLayoutGeneration-Preprint.pdf

Any language will do, but if examples can be given Javascript is preferred (as it is the language i am currently working with)

A similar question is this one: What is an efficient packing algorithm for packing rectangles into a polygon?


texts: How to bundle a HTML5 JavaScript game as native Windows application?

texts:
As the web browsers evolve, HTML5 game development with JavaScript, Canvas, webgl is increasingly becoming popular. The advantage of web-based games compared to native apps is that they run on multiple platforms, and you don't have to fiddle with OS-specific libraries or programming environments.

You can already sell your web games via the chrome web store, but I think it's too unpopular yet for being profitable for indie game developers.

I think you may reach a larger crowd by selling your games at the Mac App Store or Steam, but therefore you have to bundle it as standalone application.

For mac, you can easily bundle your HTML5 games as native app by using the Apple's WebView component. Here is an example on how to do that.

Now I wonder: is there an equivalent way for Windows platform?


texts: Simulate Keyboard Button Press [SDL Library]

texts:
I am trying to simulate an SDL keyboard button press (using C). I have looked up the SDL info pages online but I still don't have anything that consistently works.

I have the following (removed the interrupt handling, creation of windows etc.)

while(1){
    SDL_Event user_event;
    user_event.type = SDL_SCANCODE_LEFT;

    SDL_PushEvent(&user_event);
    SDL_PumpEvents();

    const Uint8 *state = SDL_GetKeyboardState(NULL);

    if (state[SDL_SCANCODE_LEFT]) {
        printf("LEFT PRESSED");
    }
    if (state[SDL_SCANCODE_RIGHT]) {
        printf("RIGHT PRESSED");
    }
}

I never see the 'LEFT PRESSED' string printed out, although when I press the right arrow key (from keyboard) I see the respective output generated. It appears like the left key press is never being pushed on the state var.

Any help would be greatly appreciated.


texts: Removing the titlebar while using slick2d?

texts:
I recently started using slick2D in my gaming programs and a problem I have is not having the ability to remove the border/titlebar. I usually do this to create my own cutom look/ interface but if I try:

this.setUndecorated(true);

It doesnt work.

How do you acheive this?


texts: How to efficiently organize different game zones with different functionality?

texts: For now I have a list of basic data class like position in game world, dimensions, type and stuff like that, but since I am starting to implement their functionality it seems kind of a bad pattern, I need each zone to have totally different data and behaviour, use different UIs etc, is there a pattern to realize that other that just making one totally different class for each zone?


texts:
I have two objects. A dynamic player and a static ground object.

It was working for a while until I did some refactoring and suddenly my play falls right through my ground object.

Is there anything obviously wrong with the following? I have no idea what might be wrong so  if you have experienced this before, enlighten me!

Here's the initialization code of the objects:

(pixelsPerMeter is 10)

    int pixelsPerMeter = Game.instance.pixelsPerMeter;

    //create body def
    BodyDef boxDef = new BodyDef();
    boxDef.position.set(0, 0);
    boxDef.type = BodyType.DYNAMIC;

    //create shape
    PolygonShape boxShape = new PolygonShape();
    boxShape.setAsBox(this.size.width / pixelsPerMeter, this.size.height / pixelsPerMeter);

    //create body
    body = Game.instance.world.createBody(boxDef);

    //finally create the fixture
    FixtureDef boxFixture = new FixtureDef();
    boxFixture.density = 1;
    boxFixture.shape = boxShape;

    //add the fixture to the box? :\
    body.createFixture(boxFixture);

This is done twice, one for the player and once for the ground object.

The player's body type is set to BodyType.DYNAMIC while the ground is STATIC.

And of course the ground is below the body, and gravity is set to 9.8f.


texts: I need to improve my ring shop. help with array, loop & query PHP

texts:
I have an array setup which consists of 25 rings, names, stats, prices. Right now in its current form, I have a form setup with 25 radio buttons with a value of 1-25 on them, and I'm using If statements in my function to buy a ring. It works but I feel it's very inefficient because I have this code running 25 times based on $_POST['ring'] which sends the value 1-25.
    if ($rings[1][7] > $_SESSION['cash']) {
        echo "You do not have enough cash for this ring!

        GO Back!

";
        return;
    }
    if ($_POST['ring'] == 1) {
        $ringcost = $_SESSION['cash'] - $rings[1][7];
        $stmt = $pdo->prepare('UPDATE cu_cash SET cash=:cash WHERE id=:id');
        $stmt->bindParam(":cash", $ringcost);
        $stmt->bindParam(":id", $_SESSION['id']);
        $stmt->execute();

        $stmt = $pdo->prepare('UPDATE cu_users SET ring_id=:ring_id WHERE id=:id');
        $stmt->bindParam(":ring_id", $_POST['ring']);
        $stmt->bindParam(":id", $_SESSION['id']);
        $stmt->execute();
        echo "You have Successfully Purchased " . $rings[1][0] . "

        GO Back!

";
    }

Now I am wondering if there's a loop I could use to take the value from $_POST['ring'] and pull the price assign it to a variable so I can do my cash - price then update the DB with ring id & update my cash? been thinking about this for a while & I am having a hard time wrapping my head around it. Loops have always confused me, but I know they are useful!


texts: How can I match the delta rotations of two objects?

texts:
Here is the code I'm starting from:

func orientation_follow(state, current_basis : Basis, target_basis : Basis):
    var delta : Basis = target_basis * current_basis.inverse();

    var q = Quat(delta);
    var axis = Vector3(q.x, q.y, q.z);

    if (axis.length_squared() > 0.0001):  # bullet fuzzyzero() is < FLT_EPSILON (1E-5)
        axis = axis.normalized();
        var angle = 2.0 * acos(q.w);
        state.set_angular_velocity(axis * (angle / (state.get_step())));
    else:
        state.set_angular_velocity(Vector3(0,0,0));

The basis is the direction in which each vector of the object has been rotated. That is inverted and multiplied by the basis of the target object (in this case, the player's motion controller) to get the delta rotation from the object to the controller. That delta gets converted to a quaternion, from which its axis is derived and normalized before multiplying the arccosine of the quaternion's z coefficient by 2 to get the angle and finding the product of the angle and that axis (divided by delta time, which I suppose smooths the rotation a bit), setting the angular velocity per how RigidBody objects are meant to be interacted with in Godot.

At least, that's what I think is going on.

The problem is, every time you pick up an object, it essentially snaps to the rotation of the controller, because the function is interpolating the rotation of the object to the rotation of the controller every frame. So if you're trying to turn something upside-down, you have to turn your controller all the way around, instead of picking it up, putting it down partially rotated, then using your other controller to complete the rotation.

What I would like to do is get the difference in rotation in the controller between the last frame and the current frame, then apply that difference to the held object each frame, but nothing I've tried over the last few hours seems to work. The end goal is for an object to keep its rotation when initially picked up, but to rotate the same amount as the controller while held, rather than immediately snapping to the orientation as the controller as soon as it gets picked up.


texts: SetBase with a KActor descendant does not appear to function

texts:
I have a KActor descendant, which is a carging shot, kind of like in R-Type. When it starts charging, I do projectile.SetBase(Pawn) in the PlayerController where it is spawned. I've checked in the debugger, and its base is in face the pawn.

But it does not move with the pawn.

I have done this before, where I base KActors on a moving entity, and it moved with them. I must have done something differently, but I can't figure out what it was. Looking at the old code, I just did SetBase like I am now.

Any ideas where I might be going wrong?


texts:
I have been reading up on Entity System Frameworks specifically Artemis. I am trying to decide if it is right for me. I strictly work on tile based 2d pixel art games, and I don’t think they will ever be that resource intensive. I have always used standard OOP with a lot of inheritance in the past.

My understanding of the Entity System Framework right now (I am not sure if I grasp it completely yet) is:

Entities are nothing but ID's
Components are nothing but dumb data added to an entities component pool
Systems are update functions that are attached to the world to handle every entity that matches the Systems component signature

If my understanding is correct then I am having quite a bit of trouble conceptualizing adding tilemaps and AI Behavioral Trees into this framework. I will ask about AI in the future.

Should a tilemap be built into this framework? Or should it be kept separate to make it easy to generate with a tilemap editor?

If the tilemap should be built into this framework, is each tile a different entity? And the tilemap a system? Or is the tilemap itself a single entity with inheritance built off of it?

If the tilemap is sperate, what would be the best way of collision detecting entities against the external tilemap?

I understand that multiple options that I have listed might be correct, but if anybody has done this in the past they might be able to shed some light on my confusion. Maybe there is another alternative that I have not thought of?

Thank you.


texts: How to make even animations with sprite sheets in Unity 5?

texts:
When importing a sprite sheet into Unity and dividing it up, what is the best way to do so to ensure that your animation works smoothly? Is there a mathematical formula for dividing the spritesheet evenly, and should you use Grid By Cell Size or Grid By Cell Count?

Also, can the free version of TexturePacker help with organizing sprites for Unity? Or are there other alternatives to the software?


texts: How can I create hemisphere worlds (floating islands?) with 3d (or 2d)? Noise (Perlin/OpenSimplex)

texts:
I've been experimenting with noise for a while and I've gotten some terrain up: It looks like this:

What I'd like instead is to have planets like this (currently mine is in a cube shape)

My generation code actually skews the values so the top is not solid and the bottom is. I tried to reverse this but I got a giant mess, with the top being completely solid up to the worldheight and the bottom having holes caved into it. Here is my generation code:

                    float value = noise.GetPerlinFractal(worldLoc.x, worldLoc.y, worldLoc.z);

                    if (y <= waterHeight) {
                        for (int i = y; i <= waterHeight; i++) {
                            chunk.addBlock(x, i + 1, z, BlocksConfig.getInstance().getBlockRegistry().get(BlockIds.WATER));
                        }
                    }

                    if (value - ((y - 128) * 0.01) >= 0) {
                        if ((y > waterHeight && y < waterHeight + 2)) {
                            chunk.addBlock(x, y, z, BlocksConfig.getInstance().getBlockRegistry().get(BlockIds.SAND));
                        } else {
                            chunk.addBlock(x, y, z, BlocksConfig.getInstance().getBlockRegistry().get(BlockIds.GRASS));
                        }

                    }
                    if (y < 105) {
                        if ((Math.pow(noise2.GetNoise(worldLoc.x, worldLoc.y, worldLoc.z), 2) + Math.pow(noise3.GetNoise(worldLoc.x, worldLoc.y, worldLoc.z), 2)) < 0.02) {
                            if (!(chunk.getBlock(x, y + 1, z) == (BlocksConfig.getInstance().getBlockRegistry().get(BlockIds.WATER)))) {
                                chunk.addBlock(x, y, z, null);
                            }
                        }
                    }

This is done for every block in every chunk.
I'm a bit confused here and saw other ancient posts about this. However, I don't exactly understand and was wondering if someone could explain such for me. Thanks so much in advance!


texts: How can I make the objects to move at the same speed as the lines?

texts:
void Update()
    {
        if (animateLines)
        {
            counter++;
            for (int i = 0; i < allLines.Length; i++)
            {
                Vector3 endPos = allLines[i].GetComponent<EndHolder>().EndVector;
                Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
                Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

                allLines[i].GetComponent<LineRenderer>().SetPosition(1, tempPos);

                instancesToMove[i].transform.position =
                    Vector3.MoveTowards(endPos, startPos, counter / 500f * speed);
            }
        }
        else
        {
            counter = 0;
            foreach (GameObject thisline in allLines)
            {
                thisline.GetComponent<LineRenderer>().SetPosition(1, thisline.GetComponent<LineRenderer>().GetPosition(0));
            }
        }
    }

The lines are LineRenderer.

void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();

        myLine.tag = "FrameLine";
        myLine.name = "FrameLine";

        myLine.AddComponent<LineRenderer>();
        myLine.AddComponent<EndHolder>();
        myLine.GetComponent<EndHolder>().EndVector = end;
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.useWorldSpace = false;
        lr.endColor = color;
        lr.startWidth = 0.1f;//0.03f;
        lr.endWidth = 0.1f;//0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, start);
    }

So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed.

Now I want to move the instancesToMove (GameObject[] ) with the same speed as the lines but the instancesToMove are moving much slower then the lines.

I tried:

instancesToMove[i].transform.position =
                        Vector3.MoveTowards(endPos, startPos, speed);

Then

instancesToMove[i].transform.position =
                        Vector3.MoveTowards(endPos, startPos, speed * Time.deltaTime);

But it's never moving with the same lines speed.


texts: How to rotate a sprite using multi-touch with AndEngine?

texts:
I am new to Android game development. I am using AndEngine GLES-2. I have created a box with a sprite. This box is now draggable by using the code below. It works fine.

But I want multi-touch on this: I want to rotate the sprite with two fingers on that box, and to keep it draggable.

I've no idea how do do that, which way should I go?

final float centerX = (CAMERA_WIDTH - this.mBox.getWidth()) / 2;
final float centerY = (CAMERA_HEIGHT - this.mBox.getHeight()) / 2;

Box = new Sprite(centerX, centerY, this.mBox, this.getVertexBufferObjectManager()) {

    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {

        this.setPosition(pSceneTouchEvent.getX() - this.getWidth()/ 2, pSceneTouchEvent.getY() - this.getHeight() / 2);

        float pValueX = pSceneTouchEvent.getX();
        float pValueY = CAMERA_HEIGHT-pSceneTouchEvent.getY();

        float  dx = pValueX -  gun.getX();
        float  dy = pValueY -  gun.getY();

        double  Radius = Math.atan2(dy,dx);
        double Angle = Radius * 360 ;

        Box.setRotation((float)Math.toDegrees(Angle));
        return true;
    }


texts: What is technical specs for iOS platform for a game?

texts: I would like to know when a contractor ask you for a technical specs for iOS platform of a game, what's the description that you should give back to him?


texts:
I have a particle emitter on a rocket just to simulate some smoke. The rockets can be free-fired or lock onto a target and gradually steer towards the target. There is an issue that I can't seem to fix. When the rockets steer too sharply from their original trajectory the particle emitter turns off. Printing trail_particles.emitting shows true. GIF illustrating this issue:

I can share code, though I'm not sure which part would be relevant since I don't access the particle emitter in code.


texts: Limitations of p2p multiplayer games vs client-server

texts:
I am reading up on multiplayer game architecture.

So far most of the articles i've found deal with the client-server model.

I'd like to know what are the limitations for using a p2p architecture? what "class" of games are possible (or more common) to implement using it? which aren't? and in general, what are its main differences and limitations against the client-server model.


texts: reading from texture2d resource in directx11

texts:
Hi^^ i am trying to read data in resource, which i used to do well without any problems. but suddenly it is not working.

first i made immutable resource that has data in it, which is
XMFLOAT4(1,1,1,1) here.
next i made staging resource for reading.
lastly, i called map/unmap to read and store data into outputArr.

//(all HRESULT checked already)
    int WIDTH = 10, HEIGHT = 2;

    ID3D11Texture2D* resource; // create texture------------------------------
    D3D11_TEXTURE2D_DESC texDesc;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.Usage = D3D11_USAGE_IMMUTABLE;
    texDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    texDesc.Width = WIDTH;
    texDesc.Height = HEIGHT;
    texDesc.CPUAccessFlags = 0;
    texDesc.ArraySize = 1;
    texDesc.MipLevels = 1;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.MiscFlags = 0;

    XMFLOAT4* initValues = new XMFLOAT4[WIDTH * HEIGHT];
    for (int i = 0; i < WIDTH * HEIGHT; ++i) {
        initValues[i] = XMFLOAT4(1,1,1,1);
    }
    D3D11_SUBRESOURCE_DATA data;
    data.pSysMem = initValues;
    data.SysMemPitch = sizeof(XMFLOAT4)*WIDTH;
    data.SysMemSlicePitch = 0;
    device->CreateTexture2D(
        &texDesc,
        &data,
        &resource);

    ID3D11Texture2D* staging; // create texture for reading --------------------
    D3D11_TEXTURE2D_DESC stgDesc;
    stgDesc.BindFlags = 0;
    stgDesc.Usage = D3D11_USAGE_STAGING;
    stgDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    stgDesc.Width = WIDTH;
    stgDesc.Height = HEIGHT;
    stgDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    stgDesc.ArraySize = 1;
    stgDesc.MipLevels = 1;
    stgDesc.SampleDesc.Count = 1;
    stgDesc.SampleDesc.Quality = 0;
    stgDesc.MiscFlags = 0;
    device->CreateTexture2D(
        &stgDesc,
        nullptr,
        &staging);

    XMFLOAT4* outputArr = new XMFLOAT4[WIDTH*HEIGHT]; // READ-------------------
    dContext->CopyResource(staging, resource);
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
    dContext->Map(staging, 0, D3D11_MAP_READ, 0, &mappedResource);

    outputArr = reinterpret_cast<XMFLOAT4*>(mappedResource.pData);
    std::vector<XMFLOAT4> testV;
    for (int y = 0; y < HEIGHT; ++y)
    {
        for (int x = 0; x < WIDTH; ++x)
        {
            int idx = y * WIDTH + x;

            testV.push_back(outputArr[idx]);
        }
    }

    dContext->Unmap(staging, 0);

and it turns out, only when WIDTH is multiple of 16(HEIGHT doesn't seem to be matter here), it copies the data well into ALL element of array, otherwise it fill out just 0 into array until next 16 element.

For example, if width/height is 10/2,
first 10 elements of outputArr will have proper data and next 6 elements have just 0, and next another 10 elements with data, and 6 elements with 0, so on.

i haven't had any problem on dealing with resources. and struggle still.
just my humble assumption is that there might be specific alignment in number of width of resource that i miss. Or silly mistake in my process.

Hope anyone can find something from this question.
thanks


texts: How can an asset bundle's resources be destroyed after destroying the compressed bundle data?

texts:
Using:

AssetBundle.Unload( false );

Will clear the compressed asset bundle data. This, unfortunately, destroys the bundle object as well, which means nothing is keeping track of the loaded resources.

Using:

AssetBundle.Unload( true );

Will clear all resources correctly. However, it may be desirable to load the required resources, free the compressed data, and then free the loaded resources at a later time. How can this be done?


texts:
this is my method for lighting:

private void lights(GL gl) {
    float[] LightPos = {0.0f, 0.0f, -1.0f, 1.0f};
    float[] LightAmb = {0.2f, 0.2f, 0.2f, 1.0f};
    float[] LightDif = {0.6f, 0.6f, 0.6f, 1.0f};
    float[] LightSpc = {0.9f, 0.9f, 0.9f, 1.0f};

    gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, LightPos, 0);
    gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, LightAmb, 0);
    gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, LightDif, 0);
    gl.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, LightSpc, 0);

    gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, LightSpc, 0);

    gl.glEnable(GL.GL_LIGHT0);
    gl.glEnable(GL.GL_LIGHT1);
    gl.glShadeModel(GL.GL_SMOOTH);
    gl.glEnable(GL.GL_LIGHTING);
}

and i see my objects flat, no specular light.. any ideas?

ps. to render my objects:

gl.glColor3f(1f,0f,0f);
gl.glBegin(GL.GL_TRIANGLES);
for(Triangle t : tubeModel.getTriangles()) {
    gl.glVertex3f(t.v1.x, t.v1.y, t.v1.z);
    gl.glVertex3f(t.v2.x, t.v2.y, t.v2.z);
    gl.glVertex3f(t.v3.x, t.v3.y, t.v3.z);
}
gl.glEnd();

this is what i'm looking for:

this is what i get:

well it's not all black but if i rotate it becomes grey-white


texts: How do I check why is no output on screen?

texts:
I'm using OpenGL 3.3+, and I'm trying to create an orthographic projection to draw on screen. I have the model data in a buffer:

X    Y
0,   0
50,  100
100, 0

And I create my Model-View-Projection matrix as follows:

glm::mat4 projection = glm::ortho(0.f, 100.f, 0.f, 100.f);
    glm::mat4 view = glm::lookAt(
        glm::vec3(0, 0, 5),
        glm::vec3(0, 0, 0),
        glm::vec3(0, 1, 0)
    );
    glm::mat4 model = glm::mat4(1);

    glm::mat4 mvp = projection * view * model;

In my debugging efforts, I used the values from the model buffer and did the same operations the shader was doing, but on the CPU using GLM:

glm::vec4 pos(x, y, 1.0, 1.0);
posicao = mvp * posicao;

And got these results:

X    Y
-1, -1
0,   1
1,  -1

Which were as expected, as the Vertex Shader's code is plain simply multiplying the matrix by the incoming vec4(vec2(x, y), 1, 1). In my understanding, this should've outputted a triangle on my screen, but it's blank. What are some ways I can debug this?


texts:
I'm working on a self-made physics engine, and I'm wondering about the best way to calculate the penetration depth into a polygon that lies in a plane given that resolution must occur along the polygon's normal.
My current system correctly uses GJK/EPA to detect if a polygon that lies in a plane is intersecting a 3D collider. However, in a case such as the one illustrated below, EPA would not calculate the separating axis to be along the plane normal, but rather outwards parallel to the plane, as that is the direction of minimum penetration.

My first thought was to simply manually alter the resolution direction. After GJK detects a collision, I can calculate the support mapping of the polygon in the opposite direction of the plane's normal, then take its perpendicular distance from the plane as its penetration depth. However, in a case such as the one below, this would yield an incorrect penetration depth, as the support point does not project onto the plane.

What's the best way to go about getting the penetration depth into the polygon, but only considering penetration of points on the polygon that actually project onto the polygon?


texts: ScreenToWorldPoint: How much depth has to be added to screen point?

texts:
I am developing a 3rd Person Controller.
The hero's chest should be rotated towards a point on the screen.
To determine the point, I use the following code:
var mousePos = Input.mousePosition;
mousePos.z = 10; // Make sure to add some "depth" to the screen point

var aim = Camera.main.ScreenToWorldPoint(mousePos);

Then I rotate the chest like this:
Vector3 v = new Vector3(0, aim.x, 0);
Chest.Rotate(v);

It does work, but it rotates only minimally, and the the direction is inverted:  If the mouse is on the right of the screen, the chest rotates to the left and vice versa.
Also, I'm not sure how to include the model's overall rotation (but I don't know yet if that is necessary).
Does anybody have any idea what I'm doing wrong?
Edit:
When I add more depth to it, it rotates much more:
var mousePos = Input.mousePosition;
mousePos.z = 100; // Make sure to add some "depth" to the screen point

var aim = Camera.main.ScreenToWorldPoint(mousePos);

But I have no idea how much depth is actually needed.
If I add 1000, it rotates like crazy.
So I would like to know how to calculate the amount of depth that should actually be added to the screen point.


texts: Mapping a Touchinput-device in a 3D World for VR

texts:
I have a Touch-Input device which is linked to my Unity Program and a VR Device.
The Touch-Input device which is bolted somewhere BUT the position can be changed.

I can get the "2D Coordinates"  X / Y from the touch input device (from 0 to 1)

For each of those 2D coordinates I also have a 3D-VR Coordinate , grabbed by a LEAP or gloves.
(Those coordinates are not always the corner ones.)

Here the problem on a wonderful paint art:

So what I have is the 2d and 3d positions of my fingertip (on the touch and inside the 3d world

And what I need is the a 3d Object (for example Cube) with correct rotation and position.

Bonus points for Scale!


texts: What is the fastest way of reading an atomic counter?

texts: I have an atomic counter in my fragment shader that my application reads after each drawcall. I am currently using glMapBufferRange with  GL_MAP_READ_BIT set. This absolutely destroys my applications performance. To give you an idea of how often the atomic counter gets read, each drawcall consists of a million vertices.


texts:
My game is now getting to the point where I have alot of classes. Currently, I'm linking all those together through my MainGame Gamestate class. So in my MainGame class I have a Camera instance, a World instance, a Player instance etcetera. Now I know this is bad practise, as this is gonna get real dirty real quick.

What is the correct way of 'linking' loads and loads of classes and systems together?

For example:

In my MainGame class I have a GUI (own GUI library) defined called DebugMenu. Now in this menu I have an input field to change my FOV. When I click the button to update the FOV, the ClickButton event i called in the DebugMenu class which is inherited from the GUI class. To change the FOV I have to call camera.setFOV(40). This camera is an instance, so I need to find the instance that the system is using! That instance is declared in the MainGame class.

I'm using Java.


texts:
We have been facing a strange issue with physx vehicles. The game behaves correctly in almost every situation: jumps, impacts, etc.

Gravity is applied correctly downward.

But when the vehicle is put upside down in a track, in a loop or twist, somehow it's stuck to the track as if SpiderCar was playing.

Find a video of it here. And an image below:

We are using PxVehicleUpdate::updateDrive4W as coming in the framework version 3.2.2
So the call is just

void VehicleManager::updateVehicle(const PxF32 timestep,
const PxVec3& gravity,PxVehicleDrivableSurfaceToTireFrictionPairs * mSurfaceTirePairs)
{
    PxVehicleUpdates(timestep,gravity,*mSurfaceTirePairs,mNumVehicles,mVehicles);
}

Gravity is a vector (0.0,-9.8,0) being Y the vertical coordinates.
Inside it calls updateDrive4W for all the vehicles, which is about 400 lines


texts:
I am using Mirror for doing my little multi-player car racing project which I want to rename the game object automatically after the NetworkManager auto create the game object.
Here is my NetworkManager code:
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class MyNetworkManager : NetworkManager
{
    public List<GameObject> spawnPos;

    public override void OnServerAddPlayer(NetworkConnection conn)
    {
        Transform start = spawnPos[numPlayers].transform;
        GameObject player = Instantiate(playerPrefab, start.position, start.rotation);
        player.name = "car_" + (numPlayers + 1).ToString();
        NetworkServer.AddPlayerForConnection(conn, player);
    }

}

This NetworkManager works good in the Host PC. However, when the client connecting to the host, the name showing in the inspector on client PC is still like car(Clone).
Does anyone know how to deal with this problem?
Thank you for your help.


texts:
I use the following code in the python command line interpreter, but the window doesn't respond.

import pyglet
window = pyglet.window.Window()

A white window with python icon into left-upper corner appears but then it basically hangs. Windows task manager shows that this window is not responding. However the Python command prompt works well. No errors or warning messages get displayed.


texts: Determine required camera pitch/yaw change based on mouse movement and roll?

texts:
I'm sure this is going to be a pretty simple answer but I can't quite figure it out on my own. Each frame, I'm getting the mouse's distance from the center of the screen (left/up is positive) and using it to change the camera's pitch and yaw.

Then, I added camera roll. Now, if the camera is rolled 45° left, moving the mouse left needs to change both the pitch AND yaw. I know I need to use math.sin and math.cos but I can't get it to work quite right.

Pitch and yaw are relative to the world, not the camera's view.

AddYaw and AddPitch are hypothetical functions that apply world yaw/pitch to the camera. So if the camera is rolled 90 degrees left (so right is world-up), applying yaw will appear to make the camera pitch "up", which is still left according to the world.

Due to the functions available to me through the game's API, I can't just apply camera-relative pitch/yaw, I'm restricted to world-relative pitch/yaw only. Basically, it boils down to applying some trigonometry to the mouse x/y input to "rotate" the pitch and yaw values added to the camera.

-- change.x = distance mouse moved left/right in this frame
-- change.y = distance mouse moved up/down in this frame

-- Fix me!
local yawChange = math.sin(rollInRads) * change.x + math.cos(rollInRads) * change.y
local pitchChange = math.cos(rollInRads) * change.y + math.sin(rollInRads) * change.x

-- Apply pitch/yaw changes to the camera
Camera:AddYaw(yawChange)
Camera:AddPitch(pitchChange)

A few examples of what it needs to return. For clarity, yaw = left positive, right negative, pitch = up positive, down negative.

Situation 1: No roll. Moving the mouse left applies positive yaw to the camera, moving the mouse up applies positive pitch. No conversion needed since camera yaw = world yaw, camera pitch = world pitch.

Situation 2: Camera is rolled 90 degrees left. Now, positive camera yaw (left) is actually negative world pitch (down). Therefore, moving the mouse left needs to apply PITCH, not yaw. And moving the mouse up needs to apply YAW, not pitch.

Situation 3: Camera is rolled 45 degrees left. Now, the camera/world axes are a bit mixed. Moving the mouse left should apply equal amounts of negative pitch AND positive yaw so the camera's view moves left relative to its own view.


texts:
I have 2 events running through time in my game. I want that when gameover starts, this events stops running

This is my code:

- (void)onEnter
{
   [super onEnter];
   [self schedule:@selector(addStars:) interval:1.5];
   [self schedule:@selector(addBoxes:) interval:2.5];

}

-(void)gameOver
{

 //stop schedule addStars
 //stop schedule addBoxes

 }


texts: Per-Frame Function Calls versus Event Driven Messaging in Game Design

texts:
The traditional game design, as I know it, uses polymorphism and virtual functions to update game objects states. In other words, the same set of virtual functions are called in regular(ex: per-frame) intervals on every object in the game.

Recently, I discovered, that there is another - event driven messaging system available to update states of game objects. Here, the objects usually are not updated on per-frame basis. Instead, a highly efficient event messaging system is built, and game objects get updated only after receiving valid event message.

Event Driven Game Architecture is well described in: Game Coding Complete by Mike McShaffry .

Could I kindly ask for help with the following questions:

What are the advantages and disadvantages of the both approaches?
Where is one better over the other?
Is Event driven game design universal and better in all areas? Is it therefore recommended for usage even in mombile platforms?
Which one is more efficient and which is more difficult to develop?

To clarify, my question is not about removing polymorphism completely from a game design. I simply wish to understand the difference and benefit from using event driven messaging vs regular(per-frame) calls to virtual functions to update game state.

Example:
This question caused a bit of controversy here, so let me offer you example:
According to MVC, the game engine is divided into three main parts:

Application Layer (Hardware and OS communication)
Game Logic
Game View

In a racing game, the Game View is responsible for rendering the screen as quickly as possible, at least 30fps. Game View listens for player's input too. Now this happens:

Player presses fuel pedal to 80%
GameView constructs a message "Car 2 Fuel Pedal Pressed to 80%" and sends it to Game Logic.
Game Logic gets the message, evaluates, calculates new car's position and behavior and creates the following messages for GameView: "Draw Car 2 Fuel Pedal Pressed 80%", "Car 2 Sound Acceleration", "Car 2 Coordinates X, Y" ...
GameView receives the messages and processes them accordingly


texts: How to handle player input with fixed rate variable fps time step?

texts:
I've made a system which uses the ideas from "Fix your Time Step" in order update physics.  I'm having trouble finding standard methods for dealing with this when user input affects player movement outside of a time-step.

If we want to integrate player movement within the "fixed time step, variable fps" system, I guess I would have to queue up player actions somehow, when accumulation hasn't yet completed. But then how do I integrate several different player actions within said timestep?  IE lets say within timestep of N milliseconds, the player executes a move forward, move right and move backwards, where there is an infinite collidable wall in front.

I could always calculate the last input, but in this case, it wouldn't be correct to do so. The player actually should be blocked by the wall, and then moving right and back would move them to the right, and back, to the right of where only processing the last input would lead.
Similarly, if all movement was accounted for together, it might result in a player having an impossible vector for the final position, but if all moves were taken independently, there might have been a valid path (ie around a corner).
If I process all inputs then the player made during the time-step, it could conceivably be costly if they made a million tiny movements (collision check at each movement), though with exact physics (as far as a fixed time step simulation is concerned).
Even if we thought the last bullet wasn't that bad, as soon as you add multiple players to the equation, it starts looking really bad, especially with a server.

Are my only options to process all actions or only process a subset of them?


texts: Simultaneously translating and rotating sprite in Unity

texts:
I have a 2D object (a PNG file I dragged onto the screen) which is a circle I would like to move left and right when the correct side of the screen is touched and have it rotate in the respective direction while doing so. Naturally, I thought using transform.Translate and transform.Rotate would be the proper way to do this, as such:

void Update() {

    if (Input.touchCount > 0)
    {
        var touch = Input.GetTouch (0);
        if (touch.position.x < Screen.width/2)
        {
            transform.Translate (Vector3.left * Time.deltaTime);
            transform.Rotate (Vector3.forward * Time.deltaTime);
        }
        else if (touch.position.x > Screen.width/2)
        {
            transform.Translate (Vector3.right * Time.deltaTime);
            transform.Rotate (Vector3.back * Time.deltaTime);
        }
    }
}

For whatever reason, rotating left and right didn't work so I tried forward and back which at least rotated it. The problem is that the circle moves in an arc, I'm assuming because as it rotates, the direction of "right" changes. Also, the circle gets squashed into an ellipse after a bit, I assume because I'm rotating on the wrong axis. I've literally just started using Unity yesterday; what is the most concise and best way to accomplish what I'd like?


texts: How to stop a running timeline in GameMaker Studio?

texts: I am creating a game using GameMaker Studio and I need to stop a timeline that is in progress. How can I approach that with GML code?


texts: How can I delete parts of a mesh in Unity?

texts:
I am trying to make a destructible game environment; I want to delete the vertices (and triangles assorted to them) within some sphere of a given radius with its center at the contact point (in essence, just delete the part of the mesh that would be destroyed by an explosion of a projectile contacting it).

The way I'm trying to achieve it now is: take a mesh, and whenever there is a collision with it, construct a vector from each vertex to the hitpoint and measure its magnitude, if the magnitude is less than a given radius, then I add the vertex to a list (say TaggedVerts). After that I arrange the triangles array into a list of triplets. I take each vertex in TaggedVerts and translate it into its corresponding triangle number (basically its index in the mesh.vertices array) and check each triplet in the triangle list I had built earlier. If any triplet contains the tagged vertex, then I remove the whole triplet from the list. After doing this for all vertices in TaggedVerts, I put the List into an array and set mesh.triangles equal to it.

However, this method only works with a cube, and I am not quite sure it works correctly anyway since it deletes some triangles and some others it leaves intact.

Is there a better way to do this?


texts: UE4 crashing after compiling, anyway to fix?

texts: I'm working on a small game project and made a completely noob mistake and don't have a back up. Well, after compiling my most recent c++ code, the engine crashed. And now every time I try to reopen it it just crashes. I opened up the Visual Studio files and commented out the code. Is there a way to compile this to the project and get it to open again? I really don't want to have to remake the entire level.


texts: Parallelizing creation of geometry chunks in minecraft-like game

texts:
In my game I separate creation of chunks into two stages. The first is where I generate the heightmap using simplex noise and the 2nd is when I create the actual vertex buffers. I do it like this so that when creating the geometry I can always look at neighboring chunks so I can do decide things like visibility of faces.

Right now I'm working on loading chunks in the background. My first attempt was to create a simple job queue and just push all of the jobs for stage 1 first followed by all the jobs for stage 2. The problem then becomes a thread trying to start a job for the 2nd stage before all the necessary 1st stage jobs are done.

I suppose I could just have another worker thread that waits for all the 1st stage jobs to finish but that seems less than ideal. It also means I can't do anything clever like starting a stage 2 chunk job after that chunk and all surrounding chunks have gone through stage 1 instead of just waiting for all pending chunks to have gone through stage 1.

What is the correct system to use when dealing with dependencies of this kind?


texts: 2D Platform character getting "unaligned" with the map

texts:
I'm trying to make a 2D Platform game and so far I can have my character moving around in a tiled map and collisions are working too. So far so good.

The problem I'm having is that the character can get "unaligned" with the map if I spawn it without double checking the X coordinate. This means that, on certain conditions, the character could walk over a small gap (just large enough for it to fit in) on the floor.
This happens because the X speed is a constant value, so in one frame the character is standing before the gap but the next frame it's past the gap.

I can solve it by simply making sure the spawning coordinates will be aligned with the map (and the X speed allows it since the tile size is a multiple of it), but it does sound like a fishy solution to me since I may want to add power-ups in the future that increase the speed.

So I'm wondering if I'm missing something on how characters should move or maybe I should actually just double check the spawning coordinates? Or maybe it is a normal thing to happen in a game??


texts:
I have a program which simulates many bouncing balls. The balls can bounce off each other and off the sides of the container.

The problem I am having is that sometimes when two balls collide, they get stuck together, overlapping very slightly. They will not come apart on their own, but may disperse if another ball knocks into them.

Here is my collision detection and resolution code:

public void handleCollisions(){
        double xDist, yDist, distanceBetween;
        for(int i = 0; i < balls.size(); i++){
            Ball A = balls.get(i);
            for(int j = i+1; j < balls.size(); j++){
                Ball B = balls.get(j);
                xDist = Math.abs(A.getCenterX() - B.getCenterX());
                yDist = Math.abs(A.getCenterY() - B.getCenterY());
                distanceBetween = Math.sqrt(xDist*xDist + yDist*yDist);
                if(distanceBetween <= (A.radius + B.radius)){
                        double dx = A.getCenterX() - B.getCenterX();
                        double dy = A.getCenterY() - B.getCenterY();
                        double collisionAngle =  Math.atan2(dy, dx);
                        double magnitudeA =  Math.sqrt(A.xVel*A.xVel + A.yVel*A.yVel);
                        double magnitudeB =  Math.sqrt(B.xVel*B.xVel + B.yVel*B.yVel);
                        double directionA =  Math.atan2(A.yVel, A.xVel);
                        double directionB =  Math.atan2(B.yVel, B.xVel);
                        double xVelOnCollisionAxisA = magnitudeA*Math.cos(directionA - collisionAngle);
                        double yVelOnCollisionAxisA = magnitudeA*Math.sin(directionA - collisionAngle);
                        double xVelOnCollisionAxisB = magnitudeB*Math.cos(directionB - collisionAngle);
                        double yVelOnCollisionAxisB = magnitudeB*Math.sin(directionB - collisionAngle);
                        double postCollisionXVelA = ((A.mass - B.mass)*xVelOnCollisionAxisA + (B.mass*2)*xVelOnCollisionAxisB) /(A.mass + B.mass);
                        double postCollisionXVelB = ((A.mass*2) * xVelOnCollisionAxisA + (B.mass - A.mass)*xVelOnCollisionAxisB)/ (A.mass + B.mass);
                        A.xVel =  (Math.cos(collisionAngle)*postCollisionXVelA + Math.cos(collisionAngle+Math.PI/2)*yVelOnCollisionAxisA);
                        A.yVel =  (Math.sin(collisionAngle)*postCollisionXVelA + Math.sin(collisionAngle+Math.PI/2)*yVelOnCollisionAxisA);
                        B.xVel =  (Math.cos(collisionAngle)*postCollisionXVelB + Math.cos(collisionAngle+Math.PI/2)*yVelOnCollisionAxisB);
                        B.yVel =  (Math.sin(collisionAngle)*postCollisionXVelB + Math.sin(collisionAngle+Math.PI/2)*yVelOnCollisionAxisB);
                }
                }
            }
        }

So essentially, the method iterates through all possible combinations of two balls. If the distance between them is less than the sum of their radii then a collision is detected and the velocities of each ball are changed.

The next method to run will update the positions of the balls, before the above method is called again.

It appears that my problem occurs when a collision is detected, but on the next pass of the function, the ball is still seen as being inside the other ball and receives a collision whilst trying to get out.

I have tried adding this code when a collision is detected. I expected this to solve the problem by moving the balls to their last position before the collision, but the problem persists

                        A.posX -= A.xVel;
                        A.posY -= A.yVel;
                        B.posX -= B.xVel;
                        B.posY -= B.yVel;

Actually for multiple balls, I'm not sure the above snippet is a good idea anyway.


texts: Unity Quality Reduction only reduces my player sprite quality

texts:
I created a small map in tiled then imported it into Unity. A small sprite character is controlled by the player to roam about the map. I am experimenting with this for University and wanted to see the effect reducing the graphics quality had on the game and machine. So I created an executable and before playing I chose a lower quality setting. However, choosing a lower setting results in only the character becoming more pixelated, the map graphics is completely unaffected.

I assume this is to do with Tiled?

How could I reduce the quality of the map in Unity? Or does it have to be done in tiled?

**EDIT

The map was imported via Tiled2Unity.


texts: How to add a scrolling camera to a 2D Java game?

texts:
I am attempting to create a game where the camera follows the player, always making sure the player is in the center of the screen. How would I go about this? This game is a 2D Java game, made with no engine.

I found an opensource game demonstrating what I want but I cannot work out how to add that to my game. The game is here, if you need it.

Thanks


texts: How do make a box collider align with a line renderer continuously?

texts:
I am having the issue of aligning my BoxCollider2D with my linerenderer.

I am trying to have a laser shoot using:
Physics2D.Linecast(startingPoint.transform.position, maxEndPoint.transform.position);

This works fine and the line is always shooting in the right direction and angle when I rotate the object. But, when I am drawing a box collider, the box doesn't align at the correct position.

Firstly, the boxcollider is attached as a child component of the line renderer.

I am using this code to get the size of the collider, which seems to work fine.

float lineLength = Vector3.Distance(lazer.GetPosition(1), lazer.GetPosition(0));

This code is for aligning the collider with the line renderer. I know I am supposed to get the midpoint, because that's how you control the location of the box collider, but I need to know the math to always make it align.

    lazerCollider.offset = new Vector3(0, ourHitPos.y - startingPoint.transform.position.y, 0) / 2;
    lazerCollider.size = new Vector3(lazerWidth, lineLength, 0);

I know right now I am only using the Y coordinate... I just need to know the math to make this work.


texts: Monogame intermediateSerializer with winforms

texts:
I want my xml files to be game ready on save in my winforms. Right now I am trying to serialize a simple object like this and it is accessing the XML file, but not outputting anything. Am I missing something? I have tried adding [Serializable()] to myTest and that did not work either.

using System;
using System.IO;
using System.Windows.Forms;

namespace WinformXMLIntermediateSerializer
{
 public partial class Form1 : Form
 {
    private const string filePath = "test.xml";
    private myTest mytest = new myTest();
    public Form1()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (File.Exists(filePath)) {
                XnaSerializer.Serialize(filePath, mytest);
                label1.Text = "File serialized...";
            }
        }
        catch(Exception Ex) {
            MessageBox.Show(Ex.ToString());
        }
    }
  }
}

Serialize Class:

using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using System.IO;
using System.Xml;

static class XnaSerializer
{
 public static void Serialize<T>(string filename, T data)
 {
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    using (XmlWriter writer = XmlWriter.Create(filename, settings))
    {
        IntermediateSerializer.Serialize<T>(writer, data, null);
    }
 }
}

Object to be serialized:

using Microsoft.Xna.Framework;

public class myTest
{
 private string name;
 public string Name
 {
    get { return name; }
    set { name = value; }
}

private Point tilesize;
public Point TileSize
{
    get { return tilesize; }
    set { tilesize = value; }
}

 public myTest() {
    Name = "test name";
    TileSize = new Point(32, 32);
 }
}


texts:
I know there are many threads about this but none of them seems to work for me and I spent like 2 days already on that problem. Things that I've checked:

http://wiki.unity3d.com/index.php/TerrainTransparency
http://forum.unity3d.com/threads/hollowed-mountain.7791
http://forum.unity3d.com/threads/hiding-parts-of-terrain.31734/#post-266593
http://www.blog.radiator.debacle.us/2012/08/how-to-dig-holes-in-unity3d-terrains.html
http://www.smokymonkeys.com/kyrill/index.asp?direct=22

It's like I see the way to accomplish that but can't really glue all the pieces together. It seems that to make a "hole" in terrain we have to:

Place an Cube/Plane with depth-mask shader onto our terrain (mountainside e.g)
Add collider to it and script with OnTriggerEnter/Exit where we have to ignore collision between player and terrain
Put an object with our cave system (made in 3ds/blender) inside our mount-shaped terrain and camouflage the edge of entrance with other objects e.g rocks so we wont see any artifacts.

I don't want to use voxel terrain, instead of depth-mask I could use transparent terrain texture paint option.

Do You know any working example for version 5.3.5 or could You help me somehow with it?


texts: Unity rigidbody exhibits a premature max speed

texts:
In effort to build a racing simulator, I have been working on a working model for the pistons in the engine, and have come to a bit of a stand still.

I have gone through extensive testing, through which we have "dumbed down" our prototype, in efforts to localise the actual problem.

We have a wheel, represented by a basic cylinder. I have added a second cylinder as a sort of knob, which allows us to run the system, and easily visualise its spin, using the following line;

Throughout various tests, a common observation is that the wheel does not appear to spin correctly. Using a collision plane to derive rotations per minute, we have determined that at a certain "thrust", the wheel reaches its maximum speed. Past a value of approximately 'thrust = 5,000', the wheel will not increase its speed. At present, this gives us a rotation of approximately 60 rotations per minute. Ideally, we want to be able to reach the breaking point of about 10,0000.

 rigidbody.AddTorque(transform.up * Time.deltaTime
                                  * rotatioonSpeed, ForceMode.Acceleration);

What causes the rigidbody to 'cap' its force? Everything is at default, as per various tutorials we have explored; As far as we have looked, various values might have an impact, but not to the point where speed hits a maximum on its own merit.

Incase it matters, a some extra information about the system:

We are not yet using conventional Unity measurements. While to scale, the pistons are quite larger then normal, with the cylinder housing the piston holding a length of approximately 2 meters.
Once "thrust" exceeds the maximum allowance to impact on speed, the value appears to weigh on breaking force, instead. Prior to reaching maximum speed, the user needs to "push" on the opposite direction, to reverse the rotation. It can take a second or two before the wheel slows down, and reverses its direction. The further past this maximum we go, the quicker the engine will immediately move in the reverse direction.
There is nothing else imparted on our model for this behaviour to take place. We are literally dealing with a wheel with a joiner pin on the side.
As stated, tutorials we have viewed tend to suggest that the values in the rigidbody should not effect the behaviour, this early. That said, here are our values:

Mass: 1
Drag: 0
Angular Drag: 0.05
Use Gravity: False
Is Kinematic: False
Interpolate: None
Collision Detection: Discrete
Constraints: FreezeRotationYZ

My best attempts to find a similar problem online ironically reaches a bunch of articles on users attempting to enforce a maximum speed. For best results within scope, we would hope to be able to reach infinite speeds, and separately work out whether the speed of our wheel would cause a major fault, in turn limiting the speed it would potentially reach in practice.

Personally, I suspect that the size of the object would make a difference, as unity perceives it. Another member on my team argues that because the rigidbody uses relative values, size should not make a difference. Unfortunately, this is as far as we can get in localising the problem.