texts: Minimap Around Perimeter of Screen, Code Provided

texts:
What I'm essentially trying to do is what a lot of FPS's nowadays do in regards to their HUD.  When an objective is off-screen, a small icon / symbol is shown on the perimeter of the screen, basically pointing towards the objective.

I'm working in 2D and I'm trying to get offscreen enemies (top-down) to show their positions via small points around the perimeter of the screen (a rectangle view, pretty standard).

Simply put, I'm trying to find the value of the red point when everything else is known:

Here's my code, and while it seems to be half functioning, sometimes it'll do funny things.

// Scan through enemiesRef list, and update dots to draw.
// ------------------------------------------------------
Enemy enemyRef;
float a, b, x, y;
float screenRatio = frustumWidth / frustumHeight;
float minX = topLeft.x;
float maxX = topLeft.x + frustumWidth;
float minY = topLeft.y;
float maxY = topLeft.y + frustumHeight;

// Loop through each enemy.
// ------------------------
for (int i = enemiesRef.size() - 1; i >= 0; --i)
{
    enemyRef = enemiesRef.get(i);

    // Get x and y distance to the enemy.
    // ----------------------------------
    x = enemyRef.position.x - center.x;
    y = enemyRef.position.y - center.y;

    // Check if the enemy is on-screen and skip.
    // -----------------------------------------
    if (Math.abs(x) < halfFrustumWidth && Math.abs(y) < halfFrustumHeight)
        continue;

    // Determine the known variable and derive the unknown.
    // ----------------------------------------------------
    float ratio = Math.abs(x) / Math.abs(y);
    if (ratio >= screenRatio)
    {
        // The a is known, the dot is on either the left or right.
        // -------------------------------------------------------
        if (enemyRef.position.x < center.x)
            a = minX;
        else
            a = maxX;

        // Calculate b.
        // ------------
        b = a * (enemyRef.position.y / enemyRef.position.x);
    }
    else
    {
        // The b is known, the dot is either on the top or bottom.
        // -------------------------------------------------------
        if (enemyRef.position.y < center.y)
            b = minY;
        else
            b = maxY;

        // Calculate a.
        // ------------
        a = b / (enemyRef.position.y / enemyRef.position.x);
    }
}

It seems the code accurately detects whether the point should be on the top / left / bottom / right, but if the object is far enough off screen (as in, it's both past the upper boundary of the view and the left boundary view at the same time, for example), the dot on the map just flies off the screen (for example, to the left, it's x coordinates going into negatives).

I believe the error lies somewhere in calculating a or b:

a = b / (enemyRef.position.y / enemyRef.position.x);
b = a * (enemyRef.position.y / enemyRef.position.x);

Whether it be with the signs of the values, or if the values I'm calculating are just wrong, etc, I don't know.


texts:
I have created a simple camera class, moved it from my C# (XNA) source to C++ for d3d.

Commonly it is okay, but something is wrong with rotation.
If i increase its pitch/yaw values, according to received player's mouse delta (cursor move), it rotates incorrect. It rotates 'around' 'world center', not position. 'world center' is changed if i change camera position.

After i move mouse left, camera is rotated like around 0;0;0 instead of own position.

XMVECTOR m_vecPosition; // x,y,z camera pos
float m_fYaw, m_fPitch;// rotation

view matrix update function:

#define VectorForward       XMVectorSet(0,0,1,0)

XMMATRIX mtxRot = XMMatrixRotationRollPitchYaw(m_fPitch, m_fYaw, 0);
XMVECTOR vecPos = XMVector3Transform(m_vecPosition, mtxRot);
XMVECTOR vecLookAt = XMVector3Transform(VectorForward, mtxRot);//'forward' transformed
vecLookAt += vecPos;
XMVECTOR vecUp = XMVector3Transform(VectorUp, mtxRot);
m_mtxView = XMMatrixLookAtLH(vecPos, vecLookAt, vecUp);

In XNA project my camera worked fine, like in FPS games, but it is impossible to move it to C++, this code definitely not correct.

And another question about camera if some one could help me:) Do i need to limit(lock) picth,yaw abs to PI*2 ? Or i what i need to do with always increasing yaw, for example ?

My camera rotates around 0;0;0, not around its position. Rotation camera makes always its look-at in center of the world. If i move camera position, i can offset its 'relative world center'. I need to make my camera properly first person, or properly third person..


texts: How to construct a matrix with the following mapping

texts:
How would I create a matrix that maps coordinates like so:
Near plane
x: [-3,3] -> [-1,1]
y: [-6,2] -> [-1,1]
z: 2 -> -1

Far plane
x: [-4,4] -> [-1,1]
y: [-4,4] -> [-1,1]
z: 0 -> 1

Visual

Result:

My current solution is a transformation in a vertex shader like below, but if it's possible to use a matrix I can keep my shaders as is.
vec4 special_projection(vec4 p){
  float ty = 0.25 * p.z;
  float tx = 0.25 * p.x;
  float xz = (tx / 3.0) * (p.z / 2.0);
  float x = tx + xz;
  float y = 0.25 * p.y + ty;
  float z = -0.5 * p.z;
  return vec4(x,y,z,1);
}


texts:
I first created a game on the iPhone and I'm now porting it to Android. I wrote most of the code in C++, but when it came to porting it wasn't so easy. The Android's way is to have two threads, one for rendering and one for updating - this due to some devices blocking when updating the hardware - while the iPhone's way is to have one thread to do it all.

My problem is that I am coming from the iPhone. When I transition, say from the Menu to the Game, I would stop the Animation (Rendering) and load up the next Manager (the Menu has a Manager and so has the Game). I could implement the same thing on Android, but I have noticed on game ports like Quake, don't do this - as far as I can tell.

What I want is someone to explain how a game like Quake can transition from the menu to the game? Does it stop rendering, load the game stuff and then start rendering again, like what I did on the iPhone? Does it load the game stuff while still rendering the menu?

Interestingly, when I did try to load a Renderer class while renderering I would get a dequeuing buffer error - which I believe to be OpenGL ES. Was I just doing something wrong or is it possible to load textures and buffers, while it's rendering?

Examples would be appreciated.


texts: 2D Physics friction on a moving platform?

texts:
I have a few basic platforming mechanics going on in this scene. I have a prefab platform with an animation that loops back and forth between two different x positions, but does not begin looping until OnCollisionStay2D activates with my player object with the tag "Red cube".

    using UnityEngine;
     using System.Collections;

public class PlatformMovement : MonoBehaviour {

        GameObject player;

        void Start()
        {
            player = GameObject.FindGameObjectWithTag("Red Cube");
        }

        void OnCollisionStay2D(Collision2D coll)
        {
            if (coll.gameObject.tag == "Red Cube")
            {
                Debug.Log ("Something has entered this zone.");
                GetComponent<Animation> ().Play ("Side To Side");
                player.transform.SetParent(transform,true);
                player.GetComponent<Rigidbody2D>().isKinematic = true;
            }
        }
    }

I would like my Red cube Player object to not slide off of the platform when it begins to move. This is solved through OnCollisionStay2D as well; however, the Red cube Player remains kinematic even after I have left the platform. I tried to solve this with

void OnCollisionExit2D(Collision2D coll)
        {
            if(coll.gameObject.tag == "Red Cube")
            {
                Debug.Log (" Honkey has left the platform.");
                player.transform.SetParent(null);
                player.GetComponent<Rigidbody2D>().isKinematic = false;

            }

But for some reason the Red Player cube still falls of... Is there an error here that I am missing? Thank you for your time!


texts: Dynamic 2d terrain loading / stitching in Unity

texts:
I'm currently working on a top down 2d game (in Unity 2d) where I'd like to build a huge terrain for the player to explore.
My question is - do you have any good practices or ideas on how to chunk the terrain, work on it in Unity (should I work on terrain chunks in different scenes etc.) and finally load it dynamically and efficiently in runtime ?


texts: How can I rasterize 3D triangles in software?

texts: I am creating a 3D software renderer, and I have a wire frame cube rendering. Now I am working on solid color rendering and I am wondering what an efficient algorithm for shading the contents of the triangles would be?


texts: How'd they do it: Millions of tiles in Terraria

texts:
I've been working up a game engine similar to Terraria, mostly as a challenge, and while I've figured out most of it, I can't really seem to wrap my head around how they handle the millions of interactable/harvestable tiles the game has at one time. Creating around 500.000 tiles, that is 1/20th of what's possible in Terraria, in my engine causes the frame-rate to drop from 60 to around 20, even tho I'm still only rendering the tiles in view. Mind you, I'm not doing anything with the tiles, only keeping them in memory.

Update: Code added to show how I do things.

This is part of a class, which handles the tiles and draws them. I'm guessing the culprit is the "foreach" part, which iterates everything, even empty indexes.

...
    public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {
        foreach (Tile tile in this.Tiles)
        {
            if (tile != null)
            {
                if (tile.Position.X < -this.Offset.X + 32)
                    continue;
                if (tile.Position.X > -this.Offset.X + 1024 - 48)
                    continue;
                if (tile.Position.Y < -this.Offset.Y + 32)
                    continue;
                if (tile.Position.Y > -this.Offset.Y + 768 - 48)
                    continue;
                tile.Draw(spriteBatch, gameTime);
            }
        }
    }
...

Also here is the Tile.Draw method, which could also do with an update, as each Tile uses four calls to the SpriteBatch.Draw method. This is part of my autotiling system, which means drawing each corner depending on neighboring tiles. texture_* are Rectangles, are set once at level creation, not each update.

...
    public virtual void Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {
        if (this.type == TileType.TileSet)
        {
            spriteBatch.Draw(this.texture, this.realm.Offset + this.Position, texture_tl, this.BlendColor);
            spriteBatch.Draw(this.texture, this.realm.Offset + this.Position + new Vector2(8, 0), texture_tr, this.BlendColor);
            spriteBatch.Draw(this.texture, this.realm.Offset + this.Position + new Vector2(0, 8), texture_bl, this.BlendColor);
            spriteBatch.Draw(this.texture, this.realm.Offset + this.Position + new Vector2(8, 8), texture_br, this.BlendColor);
        }
    }
...

Any critique or suggestions to my code is welcome.

Update: Solution added.

Here's the final Level.Draw method. The Level.TileAt method simply checks the inputted values, to avoid OutOfRange exceptions.

...
    public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {
        Int32 startx = (Int32)Math.Floor((-this.Offset.X - 32) / 16);
        Int32 endx = (Int32)Math.Ceiling((-this.Offset.X + 1024 + 32) / 16);
        Int32 starty = (Int32)Math.Floor((-this.Offset.Y - 32) / 16);
        Int32 endy = (Int32)Math.Ceiling((-this.Offset.Y + 768 + 32) / 16);

        for (Int32 x = startx; x < endx; x += 1)
        {
            for (Int32 y = starty; y < endy; y += 1)
            {
                Tile tile = this.TileAt(x, y);
                if (tile != null)
                    tile.Draw(spriteBatch, gameTime);

            }
        }
    }
...


texts: How do I use rigidbody2d.AddForce to apply a force in the direction the object is facing?

texts:
I'm trying to create a thruster on a spaceship.  It should add this thrust in the direction the thruster is facing, but I am at a loss on how to get that direction and send it to AddForce.  Am I even heading in the right direction with this script?

public float maxThrust;
FixedUpdate()
{
 float moveVertical = Input.GetAxis("Vertical") * maxThrust;
 Vector3 heading = rigidbody2D.transform.eulerAngles;
 Vector2 thrust = new Vector2(heading.normalized.x, heading.normalized.z);
 rigidbody2D.AddForce(thrust * moveVertical);
}

Maybe I'm not understanding something with EulerAngles or Vectors, but it sure seems like this would be a straightforward thing to do.


texts: Moving a sprite along a circle given by an implicit equation

texts:
I’m trying to create a hyperbolic version of Pong in a Poincaré disk, using C++ and SFML.
Here is my problem: when the ball rebounds on a paddle, I deduce two coordinates allowing me to recover the equation of the hyperbola (as a circle in the Poincaré disc), in implicit form:
$$x^2 + y^2 + ax + by + 1 = 0$$
So, I have my equation, and I can only move my sprite using its x and y Cartesian coordinates - I don’t know how to do it differently.
How can I move my sprite following this circle equation?
Moreover, I would like to represent the Poincaré metric, so the ball's velocity will also vary as a function of the metric and its position (slowing down on the screen as it gets closer to the edge of the disc where space is compressed)…


texts:
In strategy/simulation games there are often tech/research trees which allow players research new abilities/options, improve existing options and decease negative effects.

Some games seem to follow the abc approach of item 1 -> item 2 -> item 3 with minor stat changes while others make every unlocked option wildly change the way a game is played by throwing new units into the game which are able to change the balance of the game. Some make unlocking one branch block off another for the rest of the game while other will let you research everything. Some let you research multiple things while others will penalize you for switching research before it is complete. On that note tech trees can be progressive (with dedicated research over time unlocking an item) while some need you to collect enough money/points in order to unlock instantly.

What are some general guidelines for when to employ what strategy in a game? What games types of games would benefit more from one tech tree type over another and why? When should a linear tech tree be employed over a branching one?

Edit

For example a game where the main character has to build up an organisation and research technologies in secret while others are finding them and shut them down resulting in lost research laboratories, which reduce research output. The research output should increase somewhat exponentially as the game goes on as better technology is unlocked and research laboratories are upgraded. There would presumably be a very large tech tree to explore and the constant danger of losing facilities to other parties until you either unlock some endgame tech or lose everything.

Why this isn't a duplicate

Some people are marking this question as a duplicate because there is a related question about tech tree size. This question has to do more with the connections, cost and relationships between the technology options (of which size is a factor but not everything).


texts:
I need to check for collisions when firing a bullet, but I have a few questions first. My game is 2D and tile based, it also uses the XNA framework. From what I've read raycasting or continuous collision detection is the way to go for high speed bullets. XNA has a method called Ray.Intersects which takes a bounding box, does this mean that I should be starting at a point and looping through all the tiles in a line to see which tile intersects like this?

Now that example required 10 checks and now I have the information I need to know where the collision is exactly, but wait what if a person jumps in line of the ray? Well now I need to be performing these checks every frame in order to determine if a player comes in line. Assuming my game has a solid 60 FPS I'm now up to 60 checks every second or 10 checks a frame. Maybe I've shot my weapon 5 times and the wall is 50 blocks away, that would be a lot of checks.

So if you couldn't figure out what I'm getting at here these are my questions.

In order to preform raycast collisions do I start at a point (barrel of weapon) and loop through all the tiles asking "does the ray hit this tile?" until I've hit something (a wall)?
How do I optimize it or does it even need optimizing?

Remember the system needs to...

be able to obtain all the necessary information such as where does the collision take place exactly?
account for players or obstructions getting in the path of the ray.


texts: When would you use an octree in a voxel Engine?

texts:
I've been reading about Octrees, and I understand how they work (or at least I think I do). However, I can't figure out why you would use octrees instead of a simple multidimensional array.

In my project, I use chunks in my world. Every chunk is made up of 16x16x16 voxels. If I need to access a voxel, I just use the notation myChunk[x][y][z]. If I need to check neighboring voxels, I can use the same notation. I've already implemented frustum culling, face merging, and hidden surface determination. With these optimizations and this simple multidimensional array, I can render about 500 chunks at 80 fps. So, in which situation would I use octrees in this kind of Voxel Engine? Or is it useless?

I can see the purpose of octrees if I would implement LOD into my voxel engine (which I'm not planning to do). Is my lack of experience in Game Development blinding me on something?


texts: HLSL Pixel Shader that does palette swap

texts:
I have implemented a simple pixel shader which can replace a particular colour in a sprite with another colour.

It looks something like this:

sampler input : register(s0);
float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 colour = tex2D(input, coords);
    if(colour.r == sourceColours[0].r &&
    colour.g == sourceColours[0].g &&
    colour.b == sourceColours[0].b) return targetColours[0];
    return colour;
}

What I would like to do is have the function take in 2 textures, a default table, and a lookup table (both same dimensions).
Grab the current pixel, and find the location XY (coords) of the matching RGB in the default table, and then substitute it with the colour found in the lookup table at XY.

I have figured how to pass the Textures from C# into the function, but I am not sure how to find the coords in the default table by matching the colour.

Could someone kindly assist?

Thanks in advance.


texts: How to rotate an object around a fixed point?

texts:
I have a walking stick:

Some information:

The handle is fixed, it cannot move
The bottom part can move

Using the mouse click position and mouse movement, how can I rotate this stick with OpenGL?


texts: How can I orient a projectile along its flight path?

texts:
I have a projectile that is moving around the world (in a ballistics trajectory right now). I am currently keeping track of its position and velocity. I want to draw it oriented to its velocity, so that it is facing the direction it is going. This seemed like as good of a time as any to try to understand quaternions so I was attempting to solve the orientation problem using them.

Here is my drawing code:

var alignmentVector = Vector3.Normalize(velocity);
var rotationAxis = Vector3.Cross(Vector3.Up, alignmentVector);
var rotationAngle = (float)Math.Acos(Vector3.Dot(Vector3.Up, alignmentVector));
var rotationQuat = Quaternion.CreateFromAxisAngle(rotationAxis, rotationAngle);

var transform = Matrix.CreateScale(5.0f) *
                Matrix.CreateFromQuaternion(rotationQuat) *
                Matrix.CreateTranslation(position);

PresentationHelper.Draw(model, transform); //This just draws the model using the transform parameter as the world matrix

This kinda of works, but not really. In fact, I am having a hard time finding the words to describe what is happening with it. It looks like its tracking for a little while then it goes off course and becomes flattened(is that possible????)

Am I on the right track with the quaternions and can my code be fixed? If not what is a good approach to solving it?


texts:
After some months on libGDX, I chose to make a little java game library based on LWJGL.
I have already tried to do it, but got stuck on this same problem: how render text on screen.
The first time, I used Sick, but it was deprecated... how do I should do?
This time I tried this code, of couse it doesn't work (I read it on StackOverflow):
public class Starter {

private String GAME_NAME;
public String VERSION;
private int WIDTH, HEIGHT;
private static long window;

public Starter(@NotNull JJGLInfo info){
    Objects.requireNonNull(info);
    GAME_NAME = info.getGAME_NAME();
    VERSION = info.getGAME_VERSION();
    WIDTH = info.getWidth();
    HEIGHT = info.getHeight();
}

public void run(){

   System.out.println("Hello player by JJGL\nJJGL Version: " + VERSION + "\nLWJGL Version: " + Version.getVersion());

   this.init();
   this.loop();

   this.terminate();
}

private void terminate() {
    glfwFreeCallbacks(this.window);
    glfwDestroyWindow(this.window);

    glfwTerminate();
    glfwSetErrorCallback(null).free();
}

ByteBuffer pixels = this.getByteBufferFromString();
private void loop() {

    GL.createCapabilities();
    glClearColor(1f, 1f, 0f, 0f);

    while (!glfwWindowShouldClose(this.window)){
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glfwSwapBuffers(this.window);

        ByteBuffer pixels = this.getByteBufferFromString();
        glEnable(GL_TEXTURE_2D);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1000, 200, 5, GL_BLUE, GL_UNSIGNED_BYTE, pixels);
        glEnd();

        if(Input.isKeyPressed(GLFW_KEY_A))
            System.out.println(1);

        glfwPollEvents();
    }
}

private ByteBuffer getByteBufferFromString(){

    String text = "ABCD";
    int s = 256; //Take whatever size suits you.
    BufferedImage b = new BufferedImage(s, s, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g = b.createGraphics();
    g.drawString(text, 0, 0);

    int co = b.getColorModel().getNumComponents();

    byte[] data = new byte[co * s * s];
    b.getRaster().getDataElements(0, 0, s, s, data);

    ByteBuffer pixels = BufferUtils.createByteBuffer(data.length);
    pixels.put(data);
    pixels.rewind();
    return pixels;
}

/**
 * Initialize window
 */
private void init() {
    //Set Callback, when library get an error, it will be print
    GLFWErrorCallback.createPrint(System.err).set();

    //Let's initialize GLFW. Without this call, most of functions won't work
    if(!glfwInit()){
        throw new JJGLInitException("Could not initialize GLFW");
    }

    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);   //Make window hidden
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);  //Make window resizeable

    window = this.createWindow();

    glfwMakeContextCurrent(this.window);

    glfwShowWindow(this.window);
}

/**
 * Creating window. If you have passed -1 at one side,
 * it will be maximize (-1, 30 only width will be maximized)
 * @return
 */
private long createWindow() {
    //Getting info about screen
    GLFWVidMode glfwVidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    if(this.WIDTH <= -1)
        this.WIDTH = glfwVidMode.width();

    if(this.HEIGHT <= -1)
        this.HEIGHT = glfwVidMode.width();

    //Creating window
    return  glfwCreateWindow(this.WIDTH, this.HEIGHT, this.GAME_NAME, MemoryUtil.NULL, MemoryUtil.NULL);
}

public static long getWindow() { return window; }
}


texts: applyForce as long as display is pressed

texts:
In my project I have my main character body. I want it to move down on the y-axis as long as the screen is pressed. I tried it with

public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        jetski.applyForce(new Vector2(0,-1000), jetski.getWorldCenter(), true);
        return true;
    }

but that does it only once.


texts: Should the content pipeline tools be embedded in the engine?

texts:
How minimal should a games engine be?  How much of the content pipeline should be embedded in the engine?

Some use cases where the super engine might be useful:

When loading user content, the user isn't required to package up his textures, the engine will do it at load time.
A script requests a font at a much larger size than was pre-generated, the engine could parse the ttf file ad build a new texture atlas.
Halo forge.

None of this is free of course.  This requires your content pipeline tools to written in C++.  Support libraries you use in the pipeline need to be compiled for use on the device.  It requires the content generation to be not buggy.  And it generally makes your engine larger and unwieldy.
What are some other pros and cons?
Do the pros outweigh the cons?

Some specific questions:

Should engine be capable of loading various image formats?  A TGA only loader is pretty easy to hand code.
What about audio formats?  Is it feasible to only support loading wav files?  What about ambient music files which are often huge.
Should the engine be capable of dynamic TTF parsing and atlas generation?
Texture packing.


texts:
I'm having some trouble with vertical movement. I'm trying to add double-jumping but none of the scenarios online seem to be working, and I can only ever manage to get a single jump. Here's my code:

using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {
//public float speed;
CharacterController controller;
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
public bool candoublejump = true;
public int jumptime = 0;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
    controller  = GetComponent<CharacterController>();
}

void FixedUpdate() {
    if (controller.isGrounded) {
        moveDirection = new Vector3 (Input.GetAxis ("Horizontal") * 2000, 0, Input.GetAxis ("Vertical") * 2000);
        moveDirection = transform.TransformDirection (moveDirection);
        moveDirection *= speed;
    }
    if (Input.GetButton ("Jump")) {
        if (controller.isGrounded) {
            moveDirection.y = 0;
            moveDirection.y = jumpSpeed;
            candoublejump = true;
        } else {
            if (candoublejump) {
                candoublejump = false;
                moveDirection.y = jumpSpeed;
            }
        }
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}
}

Is there something wrong with my keyboard maybe? My theory is that it's checking for the double jump in the split second after you did the first one, which isn't helpful because you're still holding the jump button.


texts: Lock mouse in center of screen, and still use to move camera Unity

texts:
I am making a program from 1st person point of view. I would like the camera to be moved using the mouse, preferably using simple code, like from XNA

var center = this.Window.ClientBounds;
 MouseState newState = Mouse.GetState();

  if (Keyboard.GetState().IsKeyUp(Keys.Escape))
  {
      Mouse.SetPosition((int)center.X, (int)center.Y);
      camera.Rotation -= (newState.X - center.X) * 0.005f;
      camera.UpDown += (newState.Y - center.Y) * 0.005f;
  }

Is there any code that lets me do this in Unity, since Unity does not support XNA, I need a new library to use, and a new way to collect this input.

this is also a little tougher, since I want one object to go up and down based on if you move it the mouse up and down, and another object to be the one turning left and right.

I am also very concerned about clamping the mouse to the center of the screen, since you will be selecting items, and it is easiest to have a simple cross-hairs in the center of the screen for this purpose.

Here is the code I am using to move right now:

using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Look")]

public class MouseLook : MonoBehaviour {

public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;

public float minimumX = -360F;
public float maximumX = 360F;

public float minimumY = -60F;
public float maximumY = 60F;

float rotationY = 0F;

void Update ()
{
    if (axes == RotationAxes.MouseXAndY)
    {
        float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

        rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
        rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

        transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
    }
    else if (axes == RotationAxes.MouseX)
    {
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
    }
    else
    {
        rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
        rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

        transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
    }
    while (Input.GetKeyDown(KeyCode.Space) == true)
    {
        Screen.lockCursor = true;
    }
}

void Start ()
{
    // Make the rigid body not change rotation
    if (GetComponent<Rigidbody>())
        GetComponent<Rigidbody>().freezeRotation = true;
}
}

This code does everything except lock the mouse to the center of the screen. Screen.lockCursor = true; does not work though, since then the camera no longer moves, and the cursor does not allow you to click anything else either.


texts:
My situation is following, I am into role play, mostly me and my friends are using World of Warcraft. Since I am a bit into Blender too, I would like to try to edit some models(armor and weapon) for private use only(!). Problem is - I have no idea how to import and export them.

So far I have found only this forums.runicgames, but it looks very outdated, and I am not sure if it will work with Warlords of Dreanor extension.

How would I go about exporting the models from WoW and importing them into Blender?


texts: SNES development: why bitplanes get scrambled?

texts:
I am following this tutorial https://georgjz.github.io/snesaa04/. I am stuck on trying to draw a sprite.
Where the end result should be this:

My end result is this:

As I have not been able to find samples of tile and palette files, I am not sure if I have done everything right.
Sprites.vra:
0b 2e 2a 3f 1e 1f 0f 3f 2e 3f 1c 1f 0c ff f3 fe
2f 00 3f 00 1f 00 3c 00 38 00 10 00 00 00 00 00

SpriteColors.pal:
fe 3f 3e 77 f8 5d 0f 49 ff 7f f8 6f 8a 6b 49 62
64 39 e0 2c 60 18 98 04 9f 0e 3e 09 2c 00 00 00

As the tutorial proposes, I use cc65 as a compiler. The files are included like this:
.segment "SPRITEDATA"
SpriteData: .incbin "Sprites.vra"
ColorData:  .incbin "SpriteColors.pal"

As I could not get bsnes working, I am using Snes9X.
As this failed, I tried to draw a plane with just one color as well to figure out the logic. I did not manage, as the colors were always scrambled.
Questions:
How should the tile/bitplane and palette files look like?
What is the checksum error my emulator throws?
As a last note: please be patient if this is basic stuff. I am ex web dev and a retro game hobbyist, and assembly code is completely foreign world to me.


texts: Audio Design and XAudio2 Performance Issues

texts:
I have a very basic understanding of audio and was hoping I could get some help to resolve a problem with the audio design in my engine. Let me give you a run-down of how I've currently got it fitting together.

I have an AudioManager that handles setting up and tear down of the XAudio2 interface as well as the master voice, and various submix voices that I can use to group sounds. I have a ResourceManager that can be used to load audio files into the required buffers ready for XAudio2 consumption. During my game, I call a method on my AudioManager to play a sound - this obtains the necessary Audio Voice and links it to the right buffer and begins playback.

The first problem I am having is that when there is a lot going on, and a lot of sounds are played at once, I get performance issues - framerates drop, and there is audio stuttering. I currently don't limit the number of concurrent sounds that can be played - can you give me any other advice on a better design, or solutions to limit impact on performance?

The second problem I am having is that if multiples of the same sound are played at the same time, it sounds like the volume has been turned up on that particular sound. I assumed this is to do with wave amplification and tried implementing a Volume Limiter effect on my submix voices. This works to a degree, and I can eliminate any distortion, but the increased volume effect is still noticeable. Can anyone suggest decent values to use for the volume limiter effects, or any other solutions to the problem?


texts: Good practices in screen states management?

texts:
I wonder what are the best ways to organize different screens in a game?

I am thinking of it like this:

Inheriting a base State class, and overriding update and render methods, to handle the current screen.
Then, under certain events a StateManager is able to activate another Screen State, and the game screen changes as only the current State is rendered.

On the activation of a new screen, effects like fading could be added, and also the same goes for its deactivation. This way a flow of screen could be made. By saying when A ends, B starts, allowing for complex animations etc.

Toughts?


texts: How can I test if an object will "fit" during pathfinding?

texts:
I'm tinkering around with a 2d game where obstacles are polygons of arbitrary shapes, sizes and locations, and movable entities (players/enemies) can also be of arbitrary sizes.

What's a good general approach for detecting whether a given entity can "fit" between two obstacles during pathfinding? Basic graph-based pathfinding algorithms like Dijkstra's or A* typically involve merely a boolean (and possibly a weight). It's not immediately clear to me what's the best way of extending that to restrict narrow passages to small entities.

Presumably each entity size would need to have its own graph of the map?

I'm not familiar with the literature on this subject but I'm sure it exists - any pointers would be welcome.


texts: Unity - UI button not triggering custom script function

texts:
I have created simple movement buttons in my game. They should trigger functions of the player's scripts, but I can't link the button to the player object/script canonically from the inspector 'cause the player is created at runtime.
So I created a custom script attached to the buttons:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ActionButton : MonoBehaviour {

    private Button btn;

    void Start()
    {
        btn = GetComponent<Button>();
        btn.onClick.AddListener(TriggerFoo);
    }

    public void TriggerFoo()
    {
        Debug.Log("Btn triggered!!!!");
    }
}

Haven't implemented yet the behavior I want to achieve with it, but even at this point the button doesn't print the string on console.

Here is how the button is set up in the inspector:

I am missing something very obvious here....?


texts: How do I import 2d character assets in unity?

texts:
I recently downloaded a 2d platform assets that came with a player model. The character came in a lot of pieces like an image of eye, another for torso, etc. How do I go about making these images an actual character. The asset also came with a few animations like blinking, jumping, etc. How do I apply these?
I'm new to unity and game development(started about a few days ago) so please help even if this may sound like a really dumb question.

I use Unity BTW if it changes what the answer would be.

Link to asset:  https://assetstore.unity.com/packages/2d/environments/free-platform-game-assets-85838


texts: What size should I scale my sprites to before importing them to Unity?

texts:
I'm developing a game with an 8bit look. I want to target iOS and Android devices.

The real resolution for my backgrounds is 108 x 192.

Should I should put them in that same resolution and scale them in Unity using FilterMode / or s there a way to make the camera use nearest neighbor?

Or should I resize all my sprites before importing to something bigger? And if so to what size? 1920 x 1080?


texts: Problem unrolling loop in compute shader

texts:
I'm pretty new to compute shaders and shader writing in general. I'm trying to write a compute shader for a procedural generation project I'm working on, it's purpose is to blend biomes together. The function works by taking a sample of points around the point it's trying to calculate, and counting up how many points of each biome are in the sample, then it uses this info to blend the biomes at the given point.
The problem is that I have to loop through all of the sample points, and I keep getting the error “forced to unroll loop, but unrolling failed.” I've tried various different things to try and fix such as using the [loop] attribute, in which case I get “can't unroll loops marked with loop attribute”, and I've tried using the [unroll()] attribute to specify the amount of iterations the loop goes through, but I get the unrolling failed message again. I was wondering if anyone could suggest a solution? Here is my code:
#pragma kernel CSMain

struct BlendInputData
{
    int x;
    int z;
    int i;
    int blendRadius;
    int biomeIndexIterat;
    int xSize;
    int zSize;
};

StructuredBuffer<BlendInputData> inputData;
StructuredBuffer<int> biomeList;
RWStructuredBuffer<float4> outputData;

static int blendRadius = inputData[0].blendRadius;
static int biomeIndexIterat = inputData[0].biomeIndexIterat;
static int xSize = inputData[0].xSize;
static int zSize = inputData[0].zSize;

int MeshIndexToBiomeIndex(int meshIndex)
{
    int biomeIndex = meshIndex;
    biomeIndex += (2 * blendRadius * blendRadius) + (blendRadius * xSize);
    biomeIndex += floor((meshIndex / (xSize + 1)) + 1) * 2 * blendRadius;
    return biomeIndex;
};

float Vector2Distance(int xOne, int yOne, int xTwo, int yTwo)
{
    float distance = sqrt(pow(xOne - xTwo, 2) + pow(yOne - yTwo, 2));
    return distance;
};

[numthreads(1, 1, 1)]

void CSMain(uint3 id : SV_DispatchThreadID)
{
    RWStructuredBuffer<float> blendedBiome;
    int x = inputData[id.x].x;
    int z = inputData[id.x].z;
    int i = inputData[id.x].i;
    int index = MeshIndexToBiomeIndex(i) - biomeIndexIterat - blendRadius;
    for (int sampleZ = -blendRadius; sampleZ <= blendRadius; sampleZ++)
    {
        for (int sampleX = -blendRadius; sampleX <= blendRadius; sampleX++)
        {
            int iterator = 1 - (floor(Vector2Distance(x, z, sampleX + x, sampleZ + z) / blendRadius));
            int biome = biomeList[index];
            blendedBiome[biome] += iterator;
            index++;
        }
        index += (biomeIndexIterat / blendRadius) - (2 * blendRadius) - 1;
    }

    float denominator = pow(blendedBiome[0], 2) + pow(blendedBiome[1], 2) + pow(blendedBiome[2], 2) + pow(blendedBiome[3], 2);
    blendedBiome[0] = pow(blendedBiome[0], 2) / denominator;
    blendedBiome[1] = pow(blendedBiome[1], 2) / denominator;
    blendedBiome[2] = pow(blendedBiome[2], 2) / denominator;
    blendedBiome[3] = pow(blendedBiome[3], 2) / denominator;

    outputData[id.x].x = blendedBiome[0];
    outputData[id.x].y = blendedBiome[1];
    outputData[id.x].z = blendedBiome[2];
    outputData[id.x].w = blendedBiome[3];
}


texts: The object can't rotate around z axis in SceneKit

texts:
I am doing an app with a functionality like a 3D compass, it can point to the direction where I want. The code is

extension AR: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {

        heading = Float(newHeading.trueHeading)

        motionManager.deviceMotionUpdateInterval = 1.0/60.0
        if motionManager.isDeviceMotionAvailable {
            motionManager.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { (devMotion, error) -> Void in
                self.node.orientation = self.orient(q: (self.motionManager.deviceMotion?.attitude.quaternion)!,angle: self.heading)

        })}

    }

}

func orient(q:CMQuaternion,angle:Float) -> SCNQuaternion{
    let gq1: GLKQuaternion = GLKQuaternionMakeWithAngleAndAxis(GLKMathDegreesToRadians(-angle), 0, 0, 1)
    // add a rotation in z axis
    let gq2: GLKQuaternion = GLKQuaternionMake(Float(q.x), Float(q.y), Float(q.z), Float(q.w))
    // the current orientation
    let qp: GLKQuaternion = GLKQuaternionMultiply(gq1, gq2)
    // get the "new" orientation
    var rq = CMQuaternion()
    rq.x = Double(qp.x)
    rq.y = Double(qp.y)
    rq.z = Double(qp.z)
    rq.w = Double(qp.w)
    return SCNQuaternion(Float(rq.x), Float(rq.y), Float(rq.z), -Float(rq.w))
}

At first I got the device's orientation to apply to my object ("node") in z axis so that it can point to the right direction. However, I figure out there is gimbal lock coming. When I rotate the device in x & y axis, the object can rotate in x & y axis as well. But if I rotate the device in z axis, there are two situations:

one, the device is holding up, the object still rotates in y axis (Seems rotation in z axis disappears).

two, the device is lying down, the object rotates in z axis.

How can I avoid first situation?


texts: Adding terrain features to a perlin noise heightmap

texts:
I'm currently using Perlin Noise to generate heightmaps and model moisture levels as well as tree density to create terrain (in the form of 2D tilemaps - think dwarf fortress).

How can I generate things like caves, or other landmarks like massive boulders or buildings?

I don't want to model these features (i.e. I don't care about the inside of the cave), I just want the game to be able to say 'there is a cave here' when you're at the x,y position of the cave, and importantly, follow rules about where caves might be (e.g. side of a mountain / rocky areas).

I also want to be able to generate this in a procedural way, similar to perlin noise, so that with any 'seed', the same landmarks will always appear.

I'm struggling to think of a way to create these features, and have them always reappear with the same seed. Does anyone have any ideas? :)


texts: Is jButton in Java suitable for a Game GUI?

texts:
Recently I have encountered the issue of trying to add a GUI into my game using Swing. The game will randomly & infrequently flash the jButton or Swing component when I add it to my jFrame. I'm not sure if this is because Swing is not double buffered like the rest of my graphics or something is interfering with Swing (The game is in a barebone state, so I'm not sure what in the game would cause this).

I noticed that Minecraft has it's own custom GUI components, should I do a similar system, or is there an alternative to Swing?

EDIT: Figured I should add the initialization code for the component.

@Override
public void init(Main main) {
    playButton = new JButton("Test", new ImageIcon(this.getClass().getResource("gui/BlankButton.png")));
    playButton.setLocation(main.getW() / 2, main.getH() / 2);
    main.add(playButton);
}


texts:
I have a Prefab called Player which has a Body and a Sword.
The game uses 2 instances of Player, Player1 and Player2.

I use Player1 to strike Player2. This is code on the sword. My hope is that Sword of Player1 will log on contct with Body of Player2. It happens but only the first hit and then i have to hit several times before another strike is logged. But when i look at log from OnTriggerStay it looks like the TriggerExit is never detected untill long after the sword is gone.

    void OnTriggerEnter(Collider other)
{
    //Play sound to confirm collision
var sm = ObjectDirectory.soundManager;
    sm.PlaySoundClip(sm.gui_02);

    Debug.Log(other.name + " - ENTER" );

}

void OnTriggerStay(Collider other)
{
    Debug.Log(other.name + " - collision" );
}

void OnTriggerExit(Collider other)
{
    Debug.Log(other.name + " - HAS LEFT" );
}

DEBUG LOG:

  Player2 - ENTER
  UnityEngine.Debug:Log(Object)
  SwordControl:OnTriggerEnter(Collider) (at Assets/Scripts/SwordControl.cs:28)

  Player2 - collision
  UnityEngine.Debug:Log(Object)
  SwordControl:OnTriggerStay(Collider) (at Assets/Scripts/SwordControl.cs:34)

  (The last debug log then repeated hundreds of times long after the sword of player 1 had withdrawn and was in no contact with player 2  )

EDIT:
Further tests shows that if i move player1 backwards away form player2 i trigger the OnTriggerExit. Even if the sword is not touching Player2 since after the blow. However even after OnTriggerExit it takes many tries untill i can get another blow registered.


texts:
I am developing a top down game similar to 8 pool billard with libgdx and box2d. How do i make a 2d ball texture look like its rolling when force is applied like this:

So it feels actually 3d ?

For example if this is our ball texture:


texts: How do I find the intersection of two lines

texts:
I have a bounding box on my character, its position in the previous frame an the current frame.  The bounding box is axis aligned.

My character is running around inside a cave, I have a list of points (lines) that represents the wall of the cave (not axis aligned)

I've got a coarse grained algorithm that tells me when some part of my character is likely to have collided with some part of the cave wall.

I do not have a fine grained algorithm to tell me specifically which line of the wall was collided with and at which point.

My current thought was that I could just create a line for each corner of the bounding box from its position in the previous frame, to its position in the current frame, then test each of these lines for intersections with any of the lines in the cave wall.

My google fu however hasn't shown me an easy formula for calculating intersections.  Have I picked a bad way to do this, or am I just bad at search?

My game is written in scala, however I can read/translate most any c style language and many scripting languages, whatever you feel like answering in


texts: Why does glGetString returns a NULL string

texts:
I am trying my hands at GLFW library. I have written a basic program to get OpenGL renderer and vendor string. Here is the code

 #include <GL/glew.h>
#include <GL/glfw.h>
#include <cstdio>
#include <cstdlib>
#include <string>

using namespace std;

void shutDown(int returnCode) {
    printf("There was an error in running the code with error %d\n",returnCode);
    GLenum res = glGetError();
    const GLubyte *errString = gluErrorString(res);
    printf("Error is %s\n", errString);
    glfwTerminate();
    exit(returnCode);
}

int main() {
    // start GL context and O/S window using GLFW helper library
    if (glfwInit() != GL_TRUE)
        shutDown(1);
    if (glfwOpenWindow(0, 0, 0, 0, 0, 0, 0, 0, GLFW_WINDOW) != GL_TRUE)
        shutDown(2);
    // start GLEW extension handler
    glewInit();

    // get version info
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf("Renderer: %s\n", renderer);
    printf("OpenGL version supported %s\n", version);

    // close GL context and any other GLFW resources
    glfwTerminate();
    return 0;
}

I googled this error and found out that we have to initialize the OpenGL context before calling glGetString(). Although I have initialized OpenGL context using glfwInit() but still the function returns a NULL string. Any ideas?

Edit
I have updated the code with error checking mechanisms. This code on running outputs the following

There was an error in running the code with error 2
Error is no error


texts:
I'm currently working on a grid for snapping objects side by side. My current script is working fine, but only for game objects which haven't been rotated.

Here is an example video of the problem:

https://vid.me/jN6D

The cube at the right has a rotation of Vector3.zero, the left one has been rotated on the Y axis.

As you can see snapping works perfectly for the right one, but at 0:15 you can see that the snapping doesn't work well for the rotated cube, that's because I've currently no idea how I can add the rotation in my current script.

Here is a snippet of the most important part of code I'm currently using to calculate the grid:

Vector3 pivotToPoint = hit.point - nearestGameObject.transform.position;

float positionX = nearestGameObject.transform.position.x +
                  Mathf.Round(pivotToPoint.x / nearestGameObject.transform.renderer.bounds.size.x) *
                  nearestGameObject.transform.renderer.bounds.size.x;

float positionZ = nearestGameObject.transform.position.z +
                  Mathf.Round(pivotToPoint.z / nearestGameObject.transform.renderer.bounds.size.z) *
                  nearestGameObject.transform.renderer.bounds.size.z;

Vector3 origin = new Vector3(positionX, 0, positionZ) + Vector3.up * 100;

if (Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity, layerMask)) {
    previewGameObject.transform.position = new Vector3(positionX, hit.point.y, positionZ);

    previewGameObject.transform.rotation = nearestGameObject.transform.rotation;
}

Maybe some of you guys have an idea how to solve this, it's driving me crazy.

p.s. Here is some guy with a similar problem, but I'm very lost when in comes to adding the solution into my code.


texts:
I created a mission in Arma 3 with Eden. I wish to run the mission on a dedicated server.
I want to create a function to fade to black, skip time, and then fade back to normal again.
Everything works except for the fading.
I have the following code in fSkipTime.sqf
params ["_targetTime", "_displayText"];
_fadeOutText = format ["Waiting until %1", _displayText];
systemChat format ["Waiting until %1...", _displayText];
[_fadeOutText, "BLACK OUT", 2] remoteExec ["cutText"];
sleep 2;
_targetTime = (_targetTime - daytime + 24 ) % 24;
[_targetTime] remoteExecCall ["skipTime", 2];
sleep 1;
[_displayText, "BLACK IN", 2] remoteExec ["cutText"];

I have the following code in the object I wish to use for fading.
init:
fSkipTime = compile preprocessFile "fSkipTime.sqf";

this addAction["Wait till Morning", {
  [6.5, "06:30"] call fSkipTime;
}];
this addAction["Wait till Noon", {
  [12, "12:00"] call fSkipTime;
}];
this addAction["Wait till Evening", {
  [18.5, "18:30"] call fSkipTime;
}];
this addAction["Wait till Midnight", {
  [0, "00:00"] call fSkipTime;
}];

When I run cutText [_fadeOutText, "BLACK OUT", 2], it runs fine.
However with remoteExec or remoteExecCall nothing happens.
How do I make it fade for everybody in multiplayer?


texts:
So I want my script to set the initial position of an object depending on the size of the screen and whatever. How do I refer to the gameobject? I know you can modify stuff like their location if the user clicks on it, but how do I refer to the gameobject right when the program starts?

Also, would it be better to have the object already exist and then move it to the right location on start, or instantiate it in the right location on start? How would I do either of these things?


texts: How can I prevent a buggy old version of my game from posting scores to the Gamecenter Leaderboards?

texts:
I found that an older version of my game has a bug that causes some crazy scores to be posted to the leaderboard. I can delete these scores by editing the acceptable range in iTunesConnect and my latest patch fixes the scores from being submitted again, but that doesn't stop users who haven't updated from posting these bad scores.

Is there a solution? Is there a way to require a minimum app version for gamecenter achievements? Is there a way to delete that leaderboard and simply make a new one for the next version?

The only solution I can think of is to limit the acceptable score range to keep most of the bad scores out, but this could potentially kill a really good legitimate score and still let in lots of bad ones.


texts: What's the proper way to check if an Entity is on top of a surface?

texts:
What would be the best way to implement gravity if I have a list of different "surfaces" which if the player is on top of acceleration will stop? Would there be a better way than to loop through all of the surfaces on the map and see if the player is colliding with it?

BTW, I'm using XNA Game studios, but pseudo code is fine.


texts:
I'm currently working with C# with the XNA framework.

I'm trying to create a list of objects that are individually target-able after they are created and set in a list and displayed on a tile map.

For example, I have a blank tile map and I cycle through the tiles and randomly set objects (we'll say a box) throughout the map. When I set the box object, I add that new iteration of Box to a Box List.

At this point I have a tile map with a series of randomly placed boxes. Within these boxes I also have randomly picked values for their name, size, color etc. And these values are correctly stored within the box object in its respective index in the List.

My question is how do I go about setting up a method for targeting/selecting a box so that when I click on any given box it's respective data values appear? I'm not worried about graphical representation of the selected object but the retrieval of the objects specific data via a mouse click on its position.

I've set up Events to handle the changing of my game states, does this require the same methodology or something all together different?

Thanks for your time.


texts: How do I get beautiful small text in XNA without using external libraries?

texts:
In XNA, the spritefont technology is horrible. Nuclex does the job so much better, but I don't want to have any external references, and I'm nearly done with my game.

When using fonts like Sansation or Quicksand, it looks terrible in smaller sizes of the fonts. It's so bad!

Is there a known workaround for this? I tried setting the fontsizes to extremely high, and then scaling them down in the spritebatch with no luck.


texts: Does the size/distance of a single object affect performance?

texts:
I have a moon that I would like to place in the sky, which will likely be anywhere from 1000-5000 triangles.

Will I experience any performance degradation if I choose to place this sphere several million units away from the player, and increase its size several thousand times? Would this giant (but distant) moon have the same performance impact as the same sphere shrunken into a ball that can fit in the player's hand?

My question is intended to be platform-agnostic, but I am working within Unity.


texts: Flowfield pathfinding behind obstacles on symmetrical grid

texts:
I use Fast iterative method to create my flow field. However when an obstacle is on the same axis as the destination, the vectors behind the obstacle point directly to the destination and ignore the obstacle. I think the following image describes the problem best:
Blue is the destination
Red rectangle is an obstacle (black dots mark blocked cells)
On the middle left you can see how the flow field points directly to the destination and ignores the obstacle.

I think this is due to the 'nature' of the eikonal equation, creating the same distance for upward/downward direction in the middle behind the obstacle. I calculate the vector by:
x = T(x - 1) - T(x + 1)
y = T(y - 1) - T(y + 1)
I currently solve it by post-processing the field and fix cells behind obstacles that point to the destination. However I'd like to know if there is a better method.
Related posts:
How does Flow Field pathfinding work?
Fix my Flow Field pathfinding


texts:
I want to make an RPG game and I would like an advice on how should I create my level-experience formula. I saw this formula http://rsdo.net/rsdonline/guides/Experience%20formula.html#PHP and I created a formula myself and I want to ask you which would be better.

    RuneScape rates                     My rates

    Level 2 - 83 xp                     Level 2 - 35
    Level 3 - 174 xp                    Level 3 - 84
    Level 4 - 276 xp                    Level 4 - 150
    Level 5 - 388 xp                    Level 5 - 238
    Level 10 - 1,154 xp                 Level 10 - 1,087
    Level 100 - 14,391,160 xp           Level 100 - 311,017

As you can see at level 100 RuneScape's xp is very big and my level 100 is equal with RuneScape's Level 61. Is it better if the xp grows very fast at one point or depends on how I make my game?


texts:
How Can I Apply Ads Different Level??
I Create A 40 Level,

Ex:

Level1 complete then load ads Interstitial
Level2 complete then load ads Interstitial
Level3 complete then load ads Rewarded
Level4 complete then load ads Rewarded
Level5 complete then load ads Interstitial
Level6 complete then load ads Interstital

follow this same pattern in further levels(40)

Code:

 public string currentscenename;

 public string nextscenename;

 public void Next()        //code for next level
  {
        int num = PlayerPrefs.GetInt("Level", 0);
        Debug.Log("Num1:" + num);
        num++;

        PlayerPrefs.SetInt("Level", num);

        if (currentscenename == nextscenename)
        {
            Next();
            Debug.Log("loadlevel");
        }
        else
        {
             if (num % 4 == 3 || num % 4 == 0)         // it is working absolutely fine
            {
                //DebugPanel.Log("num1", "num2" + num % 4);

                if (rewardBasedVideo.IsLoaded())
                {
                     rewardBasedVideo.Show();   //this line generate reward ads
                    //DebugPanel.Log("rewarded", "rewardedads");
                    //DebugPanel.Log("inside ads" , "inside ads function");
                    Debug.Log("rewarded 1");
                }
            }
            if(num % 4 == 2 || num % 4 == 1)                                                                                //1 and 2
            {
                myclass.CallAds.Instance.AdsRequest();    //this line generate interstitial ads
                DebugPanel.Log("num" , "num" + num % 4);
                Debug.Log("interstitial 2");
            }
            SceneManager.LoadScene(nextscenename);
        }
  }

**Maths:**     problem is here my condition will not be run when coming Level5 and Level10,Level15,Level20,Level25,Level30,Level35,Level40
5 mod 4 =  1
10 mod 4 = 2

Problem is when coming Level5 and Level10 then not showning ads????plz help

I m Using Google AdmobAds: https://developers.google.com/admob/unity/start

Referance:


texts: How crucial is 3D terrain in a classic RTS game?

texts: My love of RTS games is from the days of Warcraft II, C&C, etc, when top-down/isometric views were king and terrain was generally tiled and flat. More modern games - as CPU/GPU power increased - moved to fully 3D terrain but I wondered is this considered a necessity in a modern game or would a more old-school design still have mileage? 3D terrain adds tactical elements but are those essential, or typically not that important to the gameplay, or even gimmicky?


texts: How to flush changes in PlayerSettings inside Editor

texts:
I have a script which works only in the Editor. The script makes changes inside PlayerSettings. However, the changes made are flushed to the hard drive just after something in Unity is saved for example any scene.

We have a script which increments the build version. The described issue sometimes leads to the wrong version committed to Git as the changes a flushed to the disk later.

How can I flush the changes of PlayerSettings from the code?


texts:
Given the following OpenGL call stack.

According to my knowlegde, the calls to glDrawElements/Arrays are ok.(?)

But, they do not draw anything. (There is no triangle)
The calls to glBegin() and glVertex() works fine.

Full source: here


texts: How do I calculate the duration between 2 frames in an animation file

texts:
I want to find out the duration between 2 frames in animation file.
Is the following correct?
fDurationBetween2Frames = AnimationClip.length / AnimationClip.frameRate;

Thank you.


texts: Why do SDL_Textures need to be created with a renderer?

texts:
I know how to create textures in SDL, but I don't get why they need to be created with a renderer:
 SDL_CreateTexture(SDL_Renderer* renderer, ...)

When it comes to rendering, I can render my texture on every renderer, regardless from which renderer it was created on. Then why does SDL_CreateTexture require me to pass in a renderer?


texts: Basic game architechture best practices in Cocos2D on iOS

texts:
Consider the following simple game: 20 squares floating around an iPhone's screen. Tapping a square causes that square to disappear.

What's the "best practices" way to set this up in Cocos2D?

Here's my plan so far:

One Objective-c GameState singleton class (maintains list of active squares)
One CCScene (since there's no menus etc)
One CCLayer (child node of the scene)
Many CCSprite nodes (one for each square, all child nodes of the layer)
Each sprite listens for a tap on itself. Receive tap => remove from GameState

Since I'm relatively new to Cocos2D I'd like some feedback on this design. For example I'm unsure of the GameState singleton. Perhaps it's unnecessary.


texts:
As android app that will be playing animation online, it will be connected via web-socket to a server.

The question is, what is the recommend way to store animation that will be loaded by the android app?
I can send JSON formatted messaged via websocket, but as I am new to 3D animation, what format is advised for my case using LibGDX?


texts:
Let's say I have this map:

<map name="diffmap1" id="diffmap1" class="myMap">
<area shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">
<area shape="poly" coords="93,244,164,215,171,233,97,264" class="diff diff2">
</map>

and javascript:

$('.diff').click(function(e){
//code here
});

How can I make when I click on one one 'diff' to make a div with border appear around that 'diff'?

It has to calculate the position automatically, like the margin-top, margin-left and size based on the coordonates.

Any thoughts?


texts:
Is there any website containing informations related with some famous game? For information I mean how to calculate damage in a rpg for example, or how they've set camera and other tips like this!
Games I'm interested in are games like the legend of zelda, league of legends,tales of series, final fantasy, super mario, online mmorpg, halo, metroid, WoW, etc. and some indie games such as games on steam (spiral knights, bastion etc)

I think it could be usefull to have a reference based on games of a certain importance both for our games and for game development culture, in general. Thanks in advance


texts:
Is it legal to use a bitmapped version of a proprietary font (such as Arial) in a commercial app?

I'm using AngelCode's BMFont to generate a bitmapped version of a few various system installed fonts for use in an iOS game. Is that legal to do without paying for a license for the font first?


texts: How do you handle entity parent-child relationship in Ashley ECS?

texts:
In the below code example, is a parent-child relationship of an entities. Now every child should follow its parent position, and the child could be re-positioned anywhere.

Entity character; // character is a parent
Entity weapon; // weapon is a child of character

Entity gun; // gun is a parent
Entity bullet; // bullet is a parent
Entity bulletShadow; // shadow is a child of bullet

My own solution is to have an OwnershipComponent which has a Entity owner attribute, but there's a doubt in my mind that the components should only have a data. An Entity is a collection of data, if I  pass this data to components this could lead to over-killing of iteration. So I've changed my mind to use its attribute int flags, this could now be use as an id to reference to child-parent relationship.

public class OwnershipComponent implements {
    public int ownerId;
}

// Entity Manager class

public void create() {
    Entity character = createCharacter();
    createWeapon(0, 0, character.flags);
}

public void createWeapon(float x, float y, int ownerId) {
    Entity weapon = engine.createEntity();
    weapon.flags = // generated unique ID from the weapon category

    OwnershipComponent ownership = engine.createComponent(OwnershipComponent);
    ownership.ownerId = ownerId;

    weapon.add(ownership);
}

public Entity getEntityById(int id) {
    return ...
}

I could access now the parent entity by id and transform its child position relatively.

// Ownership System

public void processEntity(Entity entity, float deltaTime) {
    OwnershipComponent ownership = Mapper.ownership.get(entity);
    Entity parent = EntityManager.getEntityById(ownership.ownerId);
}


texts: Multi-pass rendering using FBO and combining resulting textures

texts:
I need to render a 3D scene and then several 2D panels that i need to compose on top of the 3D render. I looked on the web for some resource that would show how people do that but couldn't find any. In my case, I don't want to use the fixed pipeline but shaders. So here is what I do:

Create FBO and 2 textures (say)
Attach texture1 to COLOR_ATTACHMENT0 and texture2 to COLOR_ATTACHMENT1
Render-loop {
    bind FBO
    draw into COLOR_ATTACHMENT0
    clear buffers (depth and color)
    render objects

    draw into COLOR_ATTACHMENT1
    clear buffers
    render the objects that will be the 2D overlay

    draw into default frame buffer
    draw quad to display combination of texture1 and texture2
}

in the quad shader I get the 2 textures and do an alpha blending using the alpha channel of the second texture.

So my question (simple):

Is this how you typically draw different scenes/content into different textures that you can combine into a final pass before displaying the results to the frame buffer? More specifically do you use the mechanism of attaching textures to different color attachment points in the render loop, then active the point you want to draw to (COL0, COL1, etc.) and then combine the textures in the end? Is that how it's typically done?


texts: I imported both the rig and baked animation seperatly from Maya, but it's not working correctly

texts:
I am using the animation controller to bind the "jump" animation I did onto the rig itself. I don't get any errors. The animation plays. Except it seems to only affect the root joint only. Basically the model moves but not the arms or legs. They stay static. So If i have a character jumping few feet away, the entire model rig will move in jump motion(X and Y axis), but nothing happens with legs and arms.

What's going on?


texts: How to implement homing missiles with loops while in transit?

texts:
I have implemented missiles that steer towards a target, however this feels kind of boring.

I want to add loops! Loops are cool! To do this I thought I could use catmull-rom splines, but that seems very static - loops would always end up at the same position unless I made several premade patterns.

Anyone have any other ideas on how I can do this?

I'm using a simple steering function: EDITED

         var toTarget = player.Position - missile.Position;
        toTarget.Normalize();

        float turnSpeed = 0.1f;
        float momentum = 3f;
        float speed = 1f;

        currentDirection = Vector2.Lerp(lastDirection, toTarget, turnSpeed);

        currentDirection.Normalize();

        lastDirection = currentDirection;
        lastPosition = missile.Position;

        player.Update(gameTime);
        missile.Update(gameTime);

        missile.Position = lastPosition + currentDirection * speed + lastDirection * momentum;

I have tried using the player as an attractor object which kind of works - the missile orbits the player object, but it mainly looks like it's moving backwards and forwards while the player object is standing still.


texts:
in the game I am doing atm you have an area with monsters.
There are two modes to damage monsters :

tapping on them
casting spells on the ground

Tapping and damaging a monster works fine.

The problem : If I have selected a spell and want to cast it on the ground, the monster collider blocks my touch of the ground behind the monster.

My solution was to disable the monster collider when I want to cast a spell.

    GameObject[] toDisable = GameObject.FindGameObjectsWithTag ("Touch");

    foreach (GameObject g in toDisable) {
        g.GetComponent<Collider>().enabled = active;
    }

And ... it works.

Now my question is : Is this an adequate solution? They say GetComponent is slow, but I guess with 20 to 30 monsters running around it should be fine?
Anything else that could be done? Maybe there is some Unity magic I am not aware of.


texts: What is "ping pong" in the context of graphics rendering?

texts:
I have to render a scene, once per light, and blend the result of the various passes. I heard and read that one way to increase performances and render targets to use would be ping pong.

I'm new to this context. What does this mean in terms of render targets + blending?


texts: Adjusting the rate of movement of different objects on the same timer

texts:
I have a series of objects moving along the straight lines. I want to implement slight changes of velocity of each of the object. Constraint is existing model of animation. I am new to this, and not sure if it is the best way to accommodate varying speeds, but what do I know?

It is a Java application that repaints the panel every time the timer expires. Timer is set via swing.Timer object that is set by timer delay constant. Every time the game is stepped objects’ coordinates advanced by an increment constant. Most of the objects are of the same class.

Is there fairly easy way to refactor existing system to allow changing velocity for an individual object? Is there some obvious common solution I am not aware about?

Idea I am having right now is to set timer delay fairly small, and only move objects every so many cycles of animation so that the apparent speed can be adjusted by varying how often they get moved. But that seems fairly involved, and I do not think it is the most elegant solution in terms of performance what with repainting the whole frame every 3-5 milliseconds.

Can it be done by advancing the objects so many (varying) times during the certain interval (let’s say 35ms for something like 28fps), and use repaint() method to redraw just individual object? Do I need to mess with pausing animation for smoothness at higher redraw rates? Is it common practise to check for collision at larger step interval, but draw animation a lot more frequently?


texts: RPG Damage Calculation Logartihm in Java

texts:
I'm trying to make a damage calculation formula for my RPG game, there are 12 levels for both the Player and the Enemy, I've come as far as making a Reverse Exponential formula, but I want the damage to go down from slow to faster as the Players level gets closer to the level of the Enemy.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class DamageCalc {

    private static double defense;
    private static double dmg;
    private static String teststring;

    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException{
        for(int i = 1; i <= 12; ++i){
            for(int j = 1; j <= 12; ++j){
                defense = ((j * 3) * 2 + 11) * 2;
                dmg = i * 12;
                double totaldmg = getDamage(i,dmg,defense,j);
                teststring += "Player Level " + i + "\nMonster Level " + j + "\nTotal Damage " + totaldmg + "\n----------------------------------\n";
            }
        }
        PrintWriter test = new PrintWriter("testvalues.txt","UTF-8");
        test.println(teststring);
        test.close();
    }

    public static double getDamage(double level, double dmg, double defense, double enemy){
        double intdamage = (((2*level+10) / 128) * (dmg/defense) * 11 + 1) * 10;
        double damage = Math.ceil(Math.pow(intdamage,level/12) * 10);
        System.out.println(intdamage);
        return damage;
    }

}

The code just loops through the players level (int i) and the enemies level (int j), then returns the damage done. The difference in damage between level 1 and 2 is significantly higher than between 11 and 12, eventhough that should be the other way around.

EDIT: I'll explain it even further. The player starts with 12 for each stat, every level 12 get's added (dmg = level * 12). Every stat for the player has 128 points and monsters 128 points, so that's why the begin defense of a monster is 11. If the damage stat from the player is lower than the defense of the enemy, the damage will get a penalty, otherwise it will get a boost (double * (dmg/defense)).

I hope this explains it.


texts:
When I was looking on how to handle key inputs in a game loop I came across the following pattern: All native key events (up or down) get queued in an event queue that is later processed. The outcome is an array, that says for each key if the key is down or up. Pretty straight forward. I then took a look in the DOOM 3 BFG source code and it seems, they do exactly the same:

DOOM-3-BFG/neo/sys/win32/win_wndproc.cpp

LONG WINAPI MainWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) {
  int key;
  switch( uMsg ) {
      // ...
      case WM_KEYDOWN:
          // ...
          Sys_QueEvent( SE_KEY, key, true, 0, NULL, 0 );
          break;

      case WM_SYSKEYUP:
      case WM_KEYUP:
          // ...
          Sys_QueEvent( SE_KEY, key, false, 0, NULL, 0 );
          break;
      // ...
  }
  //...
}

DOOM-3-BFG/neo/framework/EventLoop.cpp

void idEventLoop::ProcessEvent( sysEvent_t ev ) {
  // track key up / down states
  if ( ev.evType == SE_KEY ) {
      idKeyInput::PreliminaryKeyEvent( ev.evValue, ( ev.evValue2 != 0 ) );
  }
  // ...
}

DOOM-3-BFG/neo/framework/KeyInput.cpp

void idKeyInput::PreliminaryKeyEvent( int keynum, bool down ) {
  keys[keynum].down = down;
}

I then started asking myself, what happens if a frame might take longer and the key down and up events happen in the same frame? Because that actually means that these events compete each other e.g. cancel each other out. How can this situation be handled or is this scenario uncommon?


texts:
I am trying to draw a full screen quad without a vertex buffer.
SV_VertexID should do the trick, although I get a weird error in my shader on the following line:

PS_IN VS(uint VertexID : SV_VertexID)// << this is the line that causes trouble
{
    PS_IN output = (PS_IN)0;

    float4 pos = float4( (VertexID << 1) & 2, VertexID & 2 ,0,1);
    output.pos = mul(pos, wvp );

    float4 t = mul(pos, texTransform);
    output.tex = float2(t.x,t.y);

    return output;
}

The error message:

invalid type used for 'SV_VertexID' input semantics, must be integral

This is how I compile the shader:

fxc.exe /Tvs_4_0_level_9_3 /EVS /Fo Texture_VS.fxo Texture.fx

I dont understand why, as the type is integral. Why do I get this compiler error?


texts: Determine where is player facing up, down or left right

texts: I have a player object who can rotate(face using mouse) up, down left right and can face straight. I am willing to know that how to determine that where is camera facing? Either it is looking up or down?? while the player is continuously moving in a up/down surface.


texts: Pygame window becomes unresponsive when I click it

texts:
I'm new to programming, python and pygame.  This is some code I wrote to draw random colored rectangles on an 800 x 600 canvas.  It does what I expected it to do but becomes unresponsive if I click anywhere on the window.  I am on a 64 bit windows 7 system running 32 bit python 2.7 with the appropriate pygame 1.9.1.

    import pygame as pg
    from random import randint as rand

    pg.init()
    screen_size = (800,600)
    canvas = pg.display.set_mode(screen_size)
    pg.display.set_caption('Random Rects')
    curEvent = pg.event.poll()
    running = True
    todraw = []

    class rect:
        def __init__(self, x, y, (width, height)):
            self.x = x
            self.y = y
            self.width = width
            self.height = height
            self.color = (rand(0,255),rand(0,255),rand(0,255))
        def topygame(self):
            return self.color,(self.x,self.y,self.x+self.width,self.y+self.height)

    for x in range(100):
        todraw.append(rect(rand(0,800), rand(0,600), (rand(0,100), rand(0,100))))

    for x in todraw:
        pg.draw.rect(canvas, *(x.topygame()))

    while running:
        pg.display.flip()
        for event in pg.event.get():
            if event.type==pg.event.QUIT:
                running = False


texts:
How to use a Rigidbody on a game object after animation in Unity?
I want to play an animation fully controlling the positioning of the elements, i.e. ignoring physics. And after an animation plays till the end I want physics to resume affecting the element.
Right now to get the expected behavior I have to remove the Animator after an animation. I thought that maybe there is a neater way to do what I want, but I did not find it, so decided to ask here.

UPDATE
I just found a better way to achieve what I want. Instead of removing the Animator component I just disable it:
animator.enabled = false;

It feels better. But still I am hoping for a neater solution.


texts: When does a game need an official age-rating?

texts: When is it required for a game to receive a rating by an official or quasi-official rating board like the PEGI or the ESRB? I know that almost every game which is sold in a brick-and-mortar store almost anywhere in the world must have an age label. But what about games which are distributed globally as download or browser-based games? Is there a reason to get a content-rating for such a game? When yes, which rating board(s) need to rate it, considering that anyone in the world can play it and each country has its own local rating system with different criteria?


texts: At same positioned game objects collision detection

texts:
In my game, I am creating two game objects at same position using Instantiate statement. Each generated object has box collider attached.

So I want to detect collision between them so I write following code.

void OnCollisionStay(Collision collisionInfo){
   print("on collision stay");
}

But this statement not called. I generate two object using following code.

BallUtility.AddNormalCommonBall (normalBallPref, Vector3.zero);
BallUtility.AddNormalCommonBall (normalBallPref, Vector3.zero);

I need help in collision detection. I already post question in unity forum but I didn't get any reply from there.


texts: Android Loading Screen: How do I use a stack to load elements?

texts:
I have some problems with figuring out what value I should put in the function:

int value_needed_to_figure_out = X;
ProgressBar.incrementProgressBy(value_needed_to_figure_out);

I've been researching about loading screens and how to use them. Some examples I've seen have implemented Thread.sleep() in a Handler.post(new Runnable()) function. To me, I got most of that concept of using the Handler to update the ProgressBar, while pretending to do some heavy crunching work. So, I kept looking.

I have read this thread here: How do I load chunks of data from an assest manager during a loading screen?

It said that I can try using a stack it needs to load, and adding a size counter as I add elements to the stack. What does it mean? This is the part where I'm totally stumped.

If anyone would provide some hints, I'll gladly appreciate it. Thanks in advance.


texts:
Overview

I have a scene manager in my game and in each 'Scene' I have a render() and a update() method for drawing and updating my game's logic.

Basically, when I want to switch to another scene, let's say, when the player progresses to the next level or going from game-over back to the main menu, I just do something like this:

SceneManager.getInstance().setCurrentScene(level2); //Where level 2 is a 'Scene' class.

I have a 'MainGame' scene who's sole purpose is to house all the methods I call from my individual levels.  So I might then do something like this:

Current method

public class Level1 extends MainGame implements Scene {

    private Resources res;
    private MyGLRenderer r;

    Level1(MyGLRenderer r, Resources res){
        super(r, res);
        this.res = res;
        this.r = r;
    }

    @Override
    public void render() {
        draw(background);
        draw(playerSprite);
        draw(blue-enemies);
    }

    @Override
    public void update(){
        super.movePlayer();
        super.moveEnemies();
        super.checkCollision();
    }

}

However, in my game, when the player survives for a certain amount of time, I want to introduce more elements into the game, so I might then have a 'level2' Scene (although strictly, from the player's perspective, the game is perceived to be one big rolling level).....

    public class Level2 extends MainGame implements Scene {

        private Resources res;
        private MyGLRenderer r;

    Level2(MyGLRenderer r, Resources res){

        super(r, res);
        this.res = res;
        this.r = r;
    }

    @Override
    public void render() {
        draw(background);
        draw(playerSprite);
        draw(blue-enemies);
        draw(pink-enemies);  //New!!!! *********************************
    }

    @Override
    public void update(){

        super.movePlayer();
        super.moveEnemies();
        super.checkCollision();
    }

}

So, as you can see, Level2 is exactly the same as Leve1 but now I'm also drawing my 'pink-enemies', I can keep doing this for 'levels' 3 through 10 but I'll end up duplicating and simply adding to each level each time.  Seems like a lot of effort just to introduce 1 or 2 new things every 'level'.

Using conditions within my render / logic?

Is there a cleaner / tidier way of achieving that which I'm trying to achieve?  I could do away with all my individual 'Level' classes altogether and just work straight out my MainGame class's Render() and Update() methods, but then I would have to have something like:

Render(){

    //Render elements common to all levels
    draw(background);
    draw(playerSprite);
    draw(blue-enemies);

    //Render specific level objects

    Switch (Level){

        case 4:{draw(giantAlienSpaceship);}
        case 3:{draw(orange-enemies);}
        case 2:{draw(pinkEnemies);break;}
    }
}

And then a similar switch in my logic.  I'm not sure about this however, as it adds additional switch/conditional statements in my rendering and seems somewhat 'amateur' however, I could be completely wrong and this may be an acceptable method that people do use.

Am I missing any other obvious cleaner / cleverer way to do this (similar to my first method but without the duplicated super method calls)


texts: How to launch a prefab at the mouse position

texts:
I want to use Instantiate(item, new Vector3(...), Quaternion.identity) to land an item at the position that was clicked. My game is using a third-person view (example).

This is the code that I think I should be using:

if(Input.GetKeyDown(KeyCode.Mouse0) && cur_items > 0){
    Instantiate(item, object_pos, Quaternion.identity);
    cur_items--;
}

mouse_pos = Input.mousePosition;
object_pos = Camera.main.WorldToScreenPoint(mouse_pos);

What am I doing wrong?


texts: How to set TextureFilter to Point to make example Bloom filter work?

texts:
I have simple app that renders some particles and now I am trying to apply the bloom shader from the xna samplers ( http://create.msdn.com/en-US/education/catalog/sample/bloom ) to it, but I am running into this exception:

"XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4."

When the BloomComponent tries to end the sprite batch in the DrawFullscreenQuad method:

        spriteBatch.Begin(0, BlendState.Opaque, SamplerState.PointWrap, null, null, effect);
        spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
        spriteBatch.End(); //<------- Exception thrown here

It seems to be related to the pixel shaders that I am using to animate the particle. In a nutshell, I have a texture2d in vector4 format that holds particle positions, and another one for velocities. Here is a snippet from that area:

        GraphicsDevice.SetRenderTarget(tempRenderTarget);
        animationEffect.CurrentTechnique = animationEffect.Techniques[technique];
        spriteBatch.Begin(SpriteSortMode.Immediate,
                          BlendState.Opaque,
                          SamplerState.PointWrap,
                          DepthStencilState.DepthRead,
                          RasterizerState.CullNone,
                          animationEffect);

        spriteBatch.Draw(randomValues, new Rectangle(0, 0, width, height), Color.White);
        spriteBatch.End();

What I comment out the code that calls the particle animation pixel shaders the bloom component runs fine. Is there some state that I need to reset to make the bloom work?


texts: Create 3D line instead of a thin line in Unity in runtime with mouse drag

texts:
I know how to use line renderer to drag and drop to create line in runtime, but the line appears to be thin when looking from the end of the line, I want to create a real line that has a thickness(think of it as a tube or pipe shape), no mater where the look direction is, they should has a thinkness. How would you achieve this effect, I've got two ideas,
1.Create a rectangle shape, then extrude this shape to create mesh during runtime, but the manipulation of mesh during runtime is too complicated for me.
or
2.Create prefabs, and spawn new prefabs and connect them along the cursor routing to make them looked as they were a continous line.
Would you suggest me of some new ideas or existing package to achieve this effect, or is the first option is the way to go? What I want to do is to make a shader editor like appearence in 3D space, what I need to create is the edges, and the edges should look 3D instead of 2D line.


texts: Developing an Asteroids successor: which languages/tools/frameworks?

texts:
Currently I'm planning to run the Asteroids successor on the Java Virtual Machine, while writing the code in Scala (because that's the language I'm fluent in).

I have looked at different options, like using one of the various OpenGL bindings or using Java2D.

Having looked at some frameworks it seems that they either are targeted at 3D development or jump-and-run style games.

Are there any useful frameworks or should I try to combine libraries from different origins and roll my own "framework"?

Are other frameworks/tools like Flash/Flex vastly superior, so that learning a new language/platform would only be a minor drawback compared to huge benefits?


texts:
I am trying to interpolate players in a multiplayer game like so:

var lastTime = now - (1000 / config.serverUpdateRate);
for (var i = 0; i < players.length; ++i) {
    tmpObj = players[i];
    var total = tmpObj.t2 - tmpObj.t1;
    var fraction = lastTime - tmpObj.t1;
    var ratio = fraction / total;
    tmpObj.x = UTILS.lerp(tmpObj.x1, tmpObj.x2, ratio);
    tmpObj.y = UTILS.lerp(tmpObj.y1, tmpObj.y2, ratio);
}

The server update rate is the frequency with which the server send the player positions. The x2 is the newest position and x1 is the position from the previous update.

Now this works fine on my localhost and on an empty server. But as soon as the game server has around 60 people on it, it begins to stutter. I am assuming that this is because the positions are coming in at an inconsistent rate. How can I adjust for that in my interpolation?

You can see the issue in action here: http://moomoo.io

I have tried to simply interpolate without lerping, but the movement felt too floaty. Also client prediction is not an option in this case


texts: Object not clamping after applying force/impulse?

texts:
I am having issue with clamping the vertical position of my character after applying force. This causes a jittery effect in my character.

There are other several ways I think of, but I dont know if its the right way.

Use translate, but ive read somewhere that if I am dealing with physics its better that to use addforce.
Add an invisible gameobject with a collider to set bounderies.

and third is clamp its movement while using addforce which in my case does not work. here is my code which I call on the update.

 rb = player.GetComponent<Rigidbody2D>();
 Vector3 clampedPOS = player.transform.position;

    clampedPOS.y = Mathf.Clamp(player.transform.position.y, -6f, 4f);
    player.transform.position = clampedPOS;

    rb.AddForce(Vector2.up * upForce, ForceMode2D.Impulse);

could someone help me with these?


texts: Is there a way to convert shader graph to shader code for older version?

texts:
Editing Shader in a graph is brilliant feature, however it's only works in Unity 2018 with Lightweight RP template.

So I want to use the shader made from shader graph in Unity 2018 to older versions, such as 2017 or 5.x.

There is a button to compile the shader to code but unfortunately when I drag into 2017 it gives me syntax error so I can't use it.

Is there a way to use the shader made from Unity 2018's graph editor to older versions of Unity?


texts: Multithreaded game fails on SwapBuffers in render thread at exit

texts:
The render loop and windows message loop run on separate threads. The way the program exits is that after PostQuitMessage is called in WM_DESTROY the message loop thread signals the render loop thread to exit. As far as I can tell before the render loop thread can even process the signal it tries SwapBuffers and that fails.

My question, is there something about how Windows processes WM_DESTROY and WM_QUIT, in maybe DefWindowProc that causes various objects associated with rendering to go away even though I haven't explicitly deleted anything? And that would explain why the rendering thread is making bad calls at exit?


texts: How do I move an object towards a moving object?

texts:
I am trying to make an AI that tries to move towards the player but I don't know how. I tried using Vector2.MoveTowards() but it just mimics my movements instead of moving towards the player. I tried everything i could think of (which was not a lot :D) but i couldn't make it move towards and touch the player! Help please :D.

Also my original code:

#pragma strict
var speed : float = 100;
var targetX : Transform;
var targetY : Transform;
var mex : Transform;
var meY : Transdorm;
function Update ()
{
var targetX = transform.position.x;
var targetY = transform.position.y;
var meX = transform.position.x;
var meY = transform.position.y;
Vector2.MoveTowards(Vector2(meX, meY), Vector2(targetX, targetY), speed);
}


texts: How to draw a 2D cross-section of a 3D object?

texts:
I am creating a game where I only want the user to see the 2D intersection of a plane with a 3D object. The goal of the game is to move this plane to a certain position and rotation, which gives a certain 2D shape. Here is a link to a website which illustrates the 2D slices of a 3D object.
How do I approach this if I only want the player to see the slice.

Just to be clear, the solution does not necessarily have to be in 3D, since the ui for the player is going to be 2D anyway


texts: Are commercial javascript games sensible?

texts:
So I love javascript as a language and how it is able to be run anywhere. I'm gonna enumerate my concerns:

Does it make sense to make money from javascript? I mean, the second I publish my game online, people can download it, and post it on their own site and put their own ads into the game.
There are rumors that Facebook is working on an HTML5 platform. Still, even if you require the use of secret keys with your online part of the game, people can still just download the source code and implement their own online version. It's a little inconvenient, but the game itself didn't lose any value. They just need to build their own community now - which should be easy with a great game.
I don't have a smartphone, can someone explain if it's possible to view the source if I publish my game as a javascript application? (maybe it's wrapped into native code by the marketplace, I would appreciate the information)

I know Flash is somewhat similar, but it's my understanding that good obfuscators can effectively make the source code so ugly that it would be a mountain of work to modify.
Native games can be cracked too of course, but that doesn't mean they have the source code. They'll still rely on my online part and my updates to the game.

Tell me I'm not paranoid :)
How can someone justify spending resources on a javascript game?


texts:
I'm not a coder, im an artist, so this stuff doesn't make a ton of sense to me. I know enough to know I don't know enough, and i'm old enough to know my brain doesn't 'get' code... that said for context of what level of help I need :) ...

I'm trying to get an AI path based on an object tag. When I instantiate the object this script is on, it should look for 'mytag' on another object in the scene, and set that as 'target'

    public class pickAItarget : VersionedMonoBehaviour
    {
        /// <summary>The object that the AI should move to</summary>
        private Transform target;
        public string mytag;
        IAstarAI ai;

        void Start()
        {
            Debug.Log(GameObject.FindWithTag("mytag"));
            GetComponent<pickAItarget>().target = GameObject.FindWithTag("mytag").transform;
        }

The script compiles fine and im able to put in the tag I want to find in the inspector but when the object instantiates I get

UnityEngine.GameObject.FindWithTag (System.String tag) (at C:/buildslave/unity/build/Runtime/Export/Scripting/GameObject.bindings.cs:195)
Pathfinding.pickAItarget.Start () (at Assets/Scripts/pickAItarget.cs:26)

I feel like I HAVE defined mytag, but obviously I don't understand something.


texts:
I have a simple 3D engine and I want to make a isometric(dimetric) game, but where tiles are not real 3D planes, but 2D images like this one:

As I understand this tile is drawn in dimetric 1:2 projection
But I can't get right camera angles in order to have view, where all given tiles would fit perfectly by pixel.
After reading this page
I've tried rotating camera relatively to itself by x=26.565deg y=45deg but that gave me bad result.

It's clearly visible, that tiles don't fit together nicely.
I've tried different value, by just handpicking them, and the closes one was x:30deg y:45deg angles.

But there is a problem with gaps between tiles. It maybe somehow related to problem, that I don't know how to calculate length of one tile edge in world space, currently when I put tiles in scene I space them by 45units, which also is a handpicked value.

You would ask, "Why do I try to do this in 3D engine?". I want to mix 2D tile and object sprites with simple 3D objects in one game. I've already did isometric terrain with 2D engine, where everything can be simply calculated and doesn't need to position a camera.


texts: How can I add a glow effect around a pair of wings in Unity without post processing?

texts: Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C# script hanging in the main camera. Any idea to implement?


texts: One index buffer with multiple vertex buffers?

texts:
I noticed that there's IASetVertexBuffers() to set multiple vertex buffers at once but there's only IASetIndexBuffer() to set one index buffer. So I assume that I can simultaneously only have one index buffer set but I can have multiple vertex buffers set at the same time.

Is that correct?
How do I use index buffer with multiple vertex buffers? I.e. what indices do I provide to use more than one vertex buffer and how do I know what buffer conrete indices refer to?

Or is this used only in the case when instead of interleaved vertex data: (Pos, Normal, Pos, Normal, Pos, Normal) I provide the data in multiple buffers: (Pos, Pos, Pos) (Normal, Normal, Normal) and conrete indices refer to the same vertices in each buffer?


texts: How does a character creator system works?

texts:
Like in Aion for example, how does it work?

Do I just need to take a basic 3D mesh of a character I created and then make some modifications to it with sliders or do I need to create different clone meshes?

Is a system like that hard to create? If it is just long and tedious work no problem I have time, but my skills are limited so I don't know if I'm able to make such a system at all.

Also what kind of scripts and programs are best to start and make some prototypes and training? Are there some that aren't compatible with others?


texts: Having trouble with 2d projection (Opengl)

texts:
I need to change the normalize coords from -1 to 1 to the width and height of my application. The reason why I want to change the normalize coords is because i think it would be a easier set position of objects and find the globalbounds of objects
my Rectangle disappear when i put my projection matrix in the vertex shader
Vertex shader code
#version 330

layout(location = 0) in vec4 position;
uniform vec2 offset;
uniform mat4 projection;

void main()
{
 vec4 translate = vec4(offset.x, offset.y, 0.0, 0.0); //Using translate to move the rectangle via
                                                      //gluniform2f
 gl_Position = projection * position + translate;
}

glm::mat4 proj = glm::ortho(-2.f, 2.f, -1.5f, 1.5f, -1.f, 1.f);
shader.setMat4("proj", proj);


texts: Importing .anim files created using the Unity Animation controls

texts:
Our artist created some .anim files using the built-in Unity Mecanim system (where you use keyframes and drag various body parts to construct the animation).

However, now we're trying to export them from her Unity program into mine so that I can incorporate them into the scene. The problem is that they're simply appearing as blank files.

Here, the files are importing and everything looks fine aside from the controller:

However, once it's imported, it just shows up as a blank/unrecognized file:

She's exporting everything as a .unitypackage and I'm importing the .unitypackage, but it doesn't work for some reason.

In addition, she was able to create a new project on her computer and import the package fine. Any ideas why mine is funking up?