texts:
I want to implement lighting via shadowmaps. I see process as:
1) render something to RenderTexture1(size as game)
2) create RenderTexture2 (custom size)
3) add it to Image2 (custom size)
4) apply "generate lightmap" shader to that image, with RenderTexture1 as additional channel
5) create RenderTexture3(size as game)
6) add it to Image3(size as game)
7) Apply "generate light from lightmap" shader, with rendered lightmap as additional channel

I have a problem on last step, seems texture passing as additional channel is not rendered with shader. however it's ok in image.

code:

create() {
    ...
    this.sourceRT = this.game.make.renderTexture(this.game.width, this.game.height);

    this.shadowMapRT = this.game.make.renderTexture(this.SHADER_SIZE, this.SHADER_SIZE);
    this.shadowMapImage = this.game.add.image(0, 0, this.shadowMapRT);
    this.shadowMapImage.filters = [this.shadowTexureShader];

    this.lightingRT = this.game.make.renderTexture(this.game.width, this.game.height);
    this.lightingImage = this.game.add.sprite(200, 0, this.lightingRT);
    this.lightingImage.filters = [this.shadowCastShader];

    this.shadowTexureShader.uniforms.iChannel0.value = this.sourceRT;
    this.shadowCastShader.uniforms.iChannel0.value = this.shadowMapRT;
}

update() {
    this.light.x = this.game.input.activePointer.x;
    this.light.y = this.game.input.activePointer.y;

    this.sourceRT.renderRawXY(this.renderGroup, 0, 0, true); // this.renderGroup is a group with shadow-casters

    this.shadowTexureShader.uniforms.uLightPosition.value = [this.light.x, this.light.y];
    this.shadowCastShader.uniforms.uLightPosition.value = [this.light.x, this.light.y];
}

Additional re-explanation with picture:

I take texture0, apply shader to it (texture1 as an additional channel), to get shadowmap. Then i want to take texture1, apply shader2 to it, with texture2 (given by shader as additional channel) to get shadows from objects.

Problem at the question mark -- instead of getting texture2 (processed by shader1) i get texture0 (still unprocessed). I want to get rendered texture2 in my shader2.


texts: Multiplace instances of an object in Game Maker with a variable changing

texts:
I want to do a level selection menu in GameMaker. There's one button for each level. Clicking on the button 1 take you to level 1, button 2 take you to level 2 and so on.

But if I duplicate the first button, all of the buttons will get you to level 1. Is it possible for multiple instances of the same object to have different variables?


texts: Unity3d. Overlay of clothes on a human model

texts:
I have:

Clothes model (jackets, shirts, sweater etc. with various
sizes,colors)
Human model with dynamic height, width, position

Need overlay the clothes' model onto a human model.

Variant with a skeleton and skin is not suitable because of different clothing options and there will be a lot of variations of the model.

Need a mathematical combination of the inside of the clothes model with the surface model of the human. Can anyone help?


texts:
When creating a sequence where text advances automatically, is there a metric which will allow me to calculate a reasonable duration to display each "sentence"?

My intuition tells me that because of the way we read, the number of words is probably more relevant than the number of characters, but I'm curious what people may have already figured out about this problem.


texts: Low Level Audio Engine Sample Rate Conversion

texts:
First off, there seems to be a sparse number of audio programming tutorials out there so if anyone knows of some good resources I would be very appreciative. Now on to the topic at hand!
I am using WASAPI for the audio engine that I am trying to develop and I am having difficulties reformatting data from a read audio file data into a format that the audio device is prepared to receive. Specifically I am wondering how games generally handle converting the sampling rate of a read audio file into the requested sampling rate of the device. I saw an example where linear interpolation was used but read elsewhere that such a filter introduces too many artifacts, so again I'm wondering what a practical algorithm would be for game design, something good enough that can be achievable in a high work load real time environment.
On a separate note, would it be safe to assume that most games store the majority of its audio assets in an uncompressed audio format to save the CPU the work of uncompressing the data or are there more benefits to be gained from having less data to load from the hard drive.
Thanks in advance for the help.


texts: Need transform matrix to translate the center of the view to a custom position within the target texture

texts:
My problem is as follows:

I want to use a single render target texture for drawing 16 viewports where I want to display the 16 different combinations of the marching squares algorithm with my 3D tiles. Each viewport it's supposed to have its own camera and be located at a custom distance from the center of each tile set and this camera should be able to rotate around their center, zoom in and out, etc.

My current issue is that my current projection setting is placing the center of the camera view in the center of the target texture, instead of locating the center of the view in the center of the rectangle corresponding to that viewport.

I assumed I just had to push a translation to the final transform in order to translate the image within the normalized screen coordinates. However, when I tried to do this, it didn't work. How should I do this?

NOTE: Currently I achieved it by using the direct3d viewports, but I'd like to know how should I do if I want to use my custom transform pipeline.


texts: What is the correct way to use glTexCoordPointer?

texts:
I'm trying to work out how to use this function glTexCoordPointer.

The man page states that I must set a pointer to the first element of the array that uses the texture cordinate.

Here is my array:

static const GLfloat GUIVertices[] = {

    //FIRST QUAD
    1.0f,  1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
   -1.0f,  1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
   -1.0f, 0.94f, 0.0f, 1.0f, 0.0f, 1.0f,
    1.0f, 0.94f, 0.0f, 1.0f, 1.0f, 1.0f,

    //2ND QUAD
    // x     y      z    w      X    Y
    1.0f,  -1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
   -1.0f,  -1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
   -1.0f, -0.94f, 0.0f, 1.0f, 0.0f, 1.0f,
    1.0f, -0.94f, 0.0f, 1.0f, 1.0f,  1.0,
};

But how do I set the pointer correctly for the fifth element on the 2nd quad first row? I was thinking something like this:

glTexCoordPointer(1, GL_FLOAT, 6, reinterpret_cast<const GLvoid *>(29 * sizeof(float)));


texts:
I'm building a 2D MORPG using JavaScript, Node JS and socket.io

To prevent cheating, I have to run all collisions for all players on my server.

I'm currently doing fairly simple square collisions like this:

  for (var i = 1 ; i < collidables.length ; i++) {
    if (y < collidables[i].y + collidables[i].z &&
        x < collidables[i].x + collidables[i].z &&
        x + z > collidables[i].x &&
        y + z > collidables[i].y) {
          // Handle collision
    }
  }

When a player collides with a wall I halve their speed and bounce them back.
This is not working optimally, but it's fine for now.

The same logic is used to check bullet collision and possibly collision with monsters in the future.

I'm currently using 3 different loops for the follwing:

Player vs Terrain collisions
Bullet vs Terrain collisions
Bullet vs Monster collisions

Since all of them have slightly different logic.

Should I put them all in the same loop or is using multiple loops fine? I feel like using multiple loops will slow down my server a lot once there will be some more terrain / players / monsters.

I chose square collisions because I think they are a lot faster than any other type of collision checking, and my game will have a LOT of collision checking.

I think I will allow between 50-100 players on a single server, with most likely hundreds of monsters and thousands of bullets flying around.

There will also be a rather big map that has to stay loaded on the server. But since the server doesn't actually have to draw anything this should be fine?
Client-side the map is split up into smaller parts and only loads the parts near the player.

My game is working fine for now, but there's no real way to test with 50 players until people actually start playing.

I'm afraid I will find out way too late that my collision checking is taking up way too much server memory and/or cpu.

How can I improve the efficiency of my collision checks?

...

Here's a preview of my game in pre-alpha, it should make my question less abstract.

http://185.115.218.199:3000/

If I need to post any more info / code, please let me know and I will do so!

I'm currently running this game on a very small test-server with 512MB RAM and 1 VCPU (can't find the specifications)
This is scalable to up to 16GB RAM and 8 VCPU's and probably beyond that.


texts: How to open auto detect LAN connections?

texts:
After sucessfully creating my first online multiplayer with servers and clients in UDP, I am wondering how LAN connections works. As it is right now, I need to open a server and forward the ports for the server if public. In LAN, they connection is possible but requires the local IP address.

However, if we take Minecraft or Starcraft, the game is able to auto detects servers on your local network.

How are they achieving this ?


texts:
What's the best way to handle game states / screens?  My problem is this:

PlayGameScreen adds a new InventoryGameScreen to the game during it's update.  This immediately adds InventoryGameScreen to the array of GameScreens.  That's throwing an exception when iterating over the array that the contents of the array have changed.

Should I have two more arrays, like screensToBeAdded and screensToBeRemoved and do all the processing for them at the end of the game loop after drawing all the other screens?


texts: Is there such thing as a design pattern for game character attributes?

texts:
I'm toying with the idea of a character based game. The characters, robots, monsters, heroes (and weapons I suppose) will all have various attributes as per a D&D game for example.

They player should be able to configure those attributes to personalize their character, so maybe they'll be given 100 points at the start to allocate how they see fit to things like strength, speed, etc...

Also, I'd like the player to be able to add additional options, like maybe shields or individual spells, things like that.

Is there a standard design pattern for things like that?

I'm hacking my way through a prototype right now, and I've been considering an Options  object that accepts an Option in the constructor, with methods addOption() and getOption.

For my implementation of Option I did the following:

class Option{

  final String optionKey;
  String optionString;
  int optionInt;
  long optionLong;
  float optionFloat;
  char optionType;

  public Option(String optionKey, Object option){

    this.optionKey = optionKey;

    if(option instanceOf String){

      optionString = (String) option;
      optionType = 's';
  }else if(option instanceOf int){

    optionInt = (int) option;
    optionType = 'i';
    }else if(option instanceOf long){

    optionLong = (long) option;
    optionType = 'l';
    }else if(option instanceOf float){

    optionFloat = (float) option;
    optionType = 'f';
    }

  }

public String getOptionKey(){
  return optionKey;
}

public String getOptionValue(){
  return optionValue;
}

public void setOptionValue(String optionValue){
  this.optionValue = optionValue;
}

public void getOptionType(){
  return optionType;
}

}

But now I'm thinking this is a bit much, and perhaps I should be using an options class that encapsulates a Hashmap instead. So maybe something like this:

class Options{

HashMap<String, Object> options;

public Options(String key, Object value){
    options = new HashMap<String, Object>();
    options.put(key, value);
}

public void putOption(String key, Object value){

    options.put(key, value);
}

public void getStringOption(String key){

    return (String) options.get(key);
}

public void getFloatOption(String key){

    return (float) options.get(key);
}

//....... and so on...

}

I'm thinking the version directly above is better, is there a standard for this type of thing?


texts:
I would like to implement threading in my XNA game but I'm not sure how things work when compiling for the XBOX 360. Could someone elaborate on this?

For example, how many threads does XBOX support? I realize that XNA uses a special version of the Compact Framework. How does this affect the code during development? Do I implement things differently when developing for XBOX than Windows?

Thank you.


texts: Can Achievement systems be implemented later in development?

texts:
I'm undecided if I want to implement this feature in my game at the time or not. I don't want the project to get to far out of control so I'm focusing on core mechanics first.

Is this a feature that is easy to implement later assuming I data drive everything and store everything?


texts: Surface of Revolution with vertex shader

texts:
Is it possible to render a surface of revolution with using a vertex shader?

I have NxM vertices, and I would like to transformate them accordingly to the function
I have to draw.

Is it possible, or i can not change the vertex position with a vertex shader?

Thanks ahead!


texts: Is there an equivalent of Unity's OnCollisionEnter() in UE4?

texts:
I've been looking for how to figure out when two objects are colliding all day.

If anyone knows how to do it I would be grateful. What I really want is a similar function to Unity's OnCollisionEnter() and a way to get a pointer to the object that I'm colliding with.


texts: Game build in unity3d project transfer from a previous developer

texts:
Can someone help or give me some idea what are the necessary deliverables from a previous developer that I need to ask regarding the game project transfer?

The situation is, there is a company that is developing our game in unity3d and it is already available in Apple store and Playstore. They developed it from scratch and on our part, we are just doing the game testing process. So now, we are going to ask them to transfer the entire project development to us. The company is in another country so we are just communicating thru emails, and we never done the communication by video calls.

And That's it. what are the things they need to transfer to us?

Thanks in advance.


texts: How do I add custom data to a ListView widget in Unreal?

texts:
I have a UserWidget object with a ListView in it.
How do I add objects add and custom data to them, such as names?


texts: DirectX9 thread lock problem with "present" and background loading new textures

texts:
Given:
Selfmade 3D engine based on DirectX9 written in C++

Task:
While render loop runs load additional textures in a background thread

Current Implementation:
- Create device with D3DCREATE_MULTITHREADED
- Ensure that loaded content is used by render thread only after loading finished

Problem:
Loading performance is very poor because DirectX calls block most of the time

More specific:
Seems that all DirectX calls are blocked for the whole duration the "Present" call waits for the vsync. That is in my case 99% of the time -> Loading thread has very few opportunities to run its DirectX calls.

Absurd observation (on first sight):
Loading performance gets much better when I deactivate vsync and the render tread runs full speed. That is because the relative portion of time the render thread is inside a DirectX function is lower.

Possible but problematic solution:
Do not let "Present" wait for the vsync, instead do a "while" loop with a non waiting "Present" and as long as it returns "D3DERR_WASSTILLDRAWING" do a short "Sleep".

But I do not like that solution:
First I am afraid it degrades maximum performance of the render loop as the resolution of "Sleep" time is limited.
Second problem is that I am using multihead rendering with several monitors and I am afraid taking away full control about vsyncing from DirectX might introduce effects like tearing on some monitors or something like that.

First question: Why?
I would bet my life that blocking whole DirectX while waiting for vsync is not neccessary especially while I am only using separated resources in the loading thread.
But, well, it is like Microsoft implemented it and I am afraid I have to deal with it.

Second question: Better ideas, anyone?
Does anybody have a better solution for this, or enough experience to tell me that my possible solution is not problematic at all or can think of a better way.

I know that Microsoft worked on these things with DirectX11 but porting the whole thing now is not an option, it would take too much time.

Thanks for your time,
Ole


texts: What's the difference between mesh and a model?

texts: Which one is created first? For example if a team worked on a graphical asset of a car, what would be a model and what would be a mesh of the car?


texts: Java High-Resolution Timer for a simple game

texts:
I want to work on a model of some kind of simple shape shooter game I would develop for either the desktop or the Android, using the libGDX library. There's something I want to incorporate into the game, and that is a countdown timer with the smallest unit in centiseconds.

The trouble I'm having is which resource to use to incorporate a fully-accurate game timer where it is in sync with real time, meaning that every second on the game timer, when the game is running at full speed, is equal to one second in real time. (I should understand what is a high-resolution timer)

Java's Swing Timer class won't do, and so are the two methods from the static System class. And I'm not very confident about the timer classes I've looked up online, unless I accidentally ran into one of them and never realized it's completely accurate.

I have practiced implementing my own countdown timer except that it ain't synchronized because I'm doing an update for every 10 milliseconds. I asked a similar question on StackOverflow, but I am getting a little too obsessed in trying to find a perfectly good timer.


texts: How do I match and clear sequences 3 adjacent coloured blocks?

texts:
I'm making a game with elements of a match-3 puzzler (such as Columns, Bejeweled or Tetris Attack).  I don't know where to begin creating an efficient algorithm for matching and clearing.

My assumptions:

Blocks of a like color can be matched horizontally, vertically, or diagonally in sets of at least 3.
Blocks are held within a grid.  They do not move horizontally.
However, blocks do move vertically due to gravity.
This is an action game, therefore we have to check up on the grid each frame.
Due to the design of my game, however, we only need to check for matches if at least one block was falling in the previous frame.

Where do I go from here?


texts:
Im trying to devise an appropriate scoring system for my game.  The game in essense has a finite number of tasks to complete (say 20) and the quicker you complete these task, the more points you get.  I had devised a basic way of doing this using bands of time multiplied by a score for that band multiplied by the number of tasks solved within that time band i.e.

(Time Band) = (Points)
1-5 sec  =    15,
5-10 secs =   10,
10-20 secs    =    5,
20-30 secs   =     3,
40 secs onwards     =     1,

So for example if I did 3 tasks in the 1-5sec band i'd get 15*3=45points, if i found 10  in the 20-30sec band i'd get 3*10=30 points.

Im sure there is a more mathematical way of doing this using powers of some kind but I just can't think how and hoping someone has already done something smilar..

Many thanks in advance


texts: draw concave polygon from set of edge points

texts:
I'm having troubles trying to rearrange a set of points where each point is part of the edge of a concave polygone. My set of points is not sorted in any order, they are just randomly put in an array. See the example right below :

My goal is to rearrange these points to be able to build a polygon correctly where the next index in the array is the next point to draw :

I don't know how to do it fast, sometime arrays are made of 200 points, and I have like 20 of these arrays (I would use this to draw islands)

Thank you in advance.


texts: How to correctly instantiate prefab in Unity

texts:
I made a prefab and drag drop it to the Tile Prefab slot as shown in the picture

In my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameGrid :MonoBehaviour
{
    private int width;
    private int height;
    private int[,] gridArray;
    private float cellSize;

    [SerializeField]
    GameObject tilePrefab;// = default;

    public GameGrid(int width, int height, float cellSize)
    {
        this.width = width;
        this.height = height;
        this.cellSize = cellSize;

        gridArray = new int[width, height];

        Debug.Log(width + " " + height);

        for(int x = 0; x < gridArray.GetLength(0); x++)
        {
            for(int z = 0; z < gridArray.GetLength(1); z++)
            {

                GameObject tile =Instantiate(tilePrefab);
                tile.transform.SetParent(transform, false);
                tile.transform.localPosition = GetWorldPosition(x,z);
            }
        }
    }

    private Vector3 GetWorldPosition(int x, int z, int y = 0)
    {
        return new Vector3(x, 0, z) * cellSize;
    }

}

1.It throw out error, ArgumentException: The Object you want to instantiate is null, it is very strange because I have the Prefab assigned in the inspector, what could ran wrong, and it is strange that the console did not tell me which line is wrong.
2.Another error is "You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed", it confused me because I did not new anything.
3.This line of code "tile.transform.SetParent(transform, false);" I copied from other resource which I do not fully understand, I looked to the Unity menu still did not get any idea of what it does, it setParent but what parent property this function tries to setup, is it trying to set its parent's transform or what?
Thanks very much I'm still new to Unity.
EDIT:
Here is my testing.cs
public class Testing : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameGrid grid = new GameGrid(20, 10, 1);
    }
}

1.Remove the default assignment is not working either.
2.Regarding to the setParent, I do not have a parent, then what parent this child is attached to, if this function will instantiate a parent, then no information is provided to the creation of the parent, still confused.


texts:
This one is kinda specific. If I'm to implement frustum culling in my game, that means each one of my cubes would need a bounding sphere. My first question is can I make the sphere so close to the edge of the cube that its still easily clickable for destroying and building? Frustum culling is easily done in XNA as I've recently learned, I just need to figure out where to place the code for the culling. I'm guessing in my method that draws all my cubes but I could be wrong. My camera class currently implements a bounding frustum which is in the update method like so

   frustum.Matrix = (view * proj);

Simple enough, as I can call that when I have a camera object in my class. This works for now, as I only have a camera in my main game class. The problem comes when I decide to move my camera to my player class, but I can worry about that later.

    ContainmentType CurrentContainmentType = ContainmentType.Disjoint;
    CurrentContainmentType = CamerasFrustrum.Contains(cubes.CollisionSphere);

Can it really be as easy as adding those two lines to my foreach loop in my draw method? Or am I missing something bigger here?

UPDATE: I have added the lines to my draw methods and it works great!! So great infact that just moving a little bit removes the whole map. Many factors could of caused this, so I'll try to break it down.

    cubeBoundingSphere = new BoundingSphere(cubePosition, 0.5f);

This is in my cube constructor. cubePosition is stored in an array, The vertices that define my cube are factors of 1 ie: (1,0,1) so the radius should be .5. I least I think it should. The spheres are created every time a cube is created of course.

    ContainmentType CurrentContainmentType = ContainmentType.Disjoint;

        foreach (Cube block in cube.cubes)
        {
            CurrentContainmentType = cam.frustum.Contains(cube.cubeBoundingSphere);

    ///more code here

     if (CurrentContainmentType != ContainmentType.Disjoint)
            {
                cube.Draw(effect);
            }

Within my draw method. Now I know this works because the map disappears, its just working wrong. Any idea on what I'm doing wrong?


texts: How can I reuse objects going off left side of screen, by putting them offscreen on the right side?

texts:
I have an array of roughly 10,000 tiles over a 2d grid. When a tile goes off screen, I'd like to recycle it by disabling the renderer, repositioning it just before it comes on screen again, then turn the renderer back on. For example, if the camera is moving right on a platformer, the tiles on the left going off screen would be recycled and repositioned on the right side just before the camera. The player could be moving in any 2d direction, up, up right, right, down right, down, down left, left, up left, thus I need to account for all directions.

    0,0--------------->100, 0
    | Move Direction--> |
    |                   |
   x|xxxxxxxxxxxxxxxxxxx|xxx  <-  Recycled objects taken
   x|xxxxxxxxxxxxxxxxxxx|xxx  <-  from left and repositioned on right
    0,-100<----------->100,-100

I've tried two approaches, one is using a wider camera view (maybe 1.3x) and using the edges with ViewportToWorldPoint and getting the player horizontal and vertical movement direction. If the camera is moving horizontally one way, my tilemanager script runs down the other side and repositions the objects on the opposite just before coming on screen. The problem here is if one is ever missed, it could go astray and then over time this leads to further problems if over time multiple are missed. I am using a tilemanager and not putting a script in each tile as it seems wasteful to have a script running in 10k+ tiles.

The other approach is literally to just scan every item in the array to see if any are outside the viewport bounding box, which seems like a huge waste of resources and not the right way to go. I have a 2d array that has just the positions saved, nonetheless scanning through any array of 10k+ each frame seems like it isn't the right way to go in terms of efficiency.

All of this work is being done as a coroutine but what is frustrating is that unity doesn't support threading as this would make this task faster as I could divide up the work more.

Is there another way anyone has used or created something that will efficiently find all objects off screen, in order to reuse them?


texts:
I want to drag an object to a perticular place.In case I release that dragged object before I reach that particular area ,the object should come to its initial place where i start to drag.  How it possible? Is there any specific motion for this?

void OnMouseDown()
{

    drag = true;
    //Debug.Log("haii ");
}
  void OnMouseDrag()
{
    if(drag)
    {
        var pos =Input.mousePosition;
        pos.x =Mathf.Clamp(pos.x,0,Screen.width);
        pos.y =Mathf.Clamp(pos.y,0,Screen.height);
        if(zdist>0)
        {
     zdist=Vector3.Distance(Camera.main.transform.position,transform.position);
            pos.z=zdist;
            pos = Camera.main.ScreenToWorldPoint(pos);
            transform.position =pos;

        }
    }
}


texts: Is 1 pixel of a height map representative of 1 vertex on the mesh?

texts: I'm trying to get my head around heightmap terrain generation. If I have a plane say 64 x 64 verts will I need to create a 64px by 64px greyscale heightmap in order to displace the geometry of the plane correctly?


texts: How can I change view to orthographic using a menu?

texts:
I'm writing the custom menu using MenuItem and I'm stuck trying to make scene view orthographic when 5 is pressed. What is the object or method I can use to set scene's view to orthographic (I don't mean the main camera, but the main view shown in the window).

This is a C# code of what I was trying to achieve:

[MenuItem("View/SetOrtho _5")]
static void SetOrtho() {
    var scene = ... //assign scene
    scene.setOrtho(true); //set orthographic view to the scene
}


texts: What would cause my graphics to stop updating when the mouse is moving?

texts:
I'm learning metro development with c++, DirectX, win8 CP, vs11 beta. I've come across some unexpected behavior:

Running the tutorial series ( Direct3D Tutorial Sample 1 ), and any sample or app for that matter, If I'm watching motion on the screen such as the cube slowly rotating, and I move the mouse, the object stops updating/rotating until I stop moving the mouse.

Here is a very short video of what I mean: http://www.screencast.com/t/cEHkVUaRcw

It even does this with the shooting sample game, which is very mouse intensive. It makes all the motion very jumpy.

I believe it has something to do with the system. I can interrupt the dispatcher from processing messages and it stops manifesting this behavior so it feels like the computer is so busy processing messages that it can't keep up with the rest of the updating. But this problem only started recently so I do not believe it is a problem with my computer's processing power.

Has anyone else experienced this and know how to resolve it or does anybody have an idea into why this is going on?

Here is the game loop code that MS ships with the sample.

while (!m_windowClosed)
{
    timer->Update();
    CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
    m_renderer->Update(timer->Total, timer->Delta);
    m_renderer->Render();
    m_renderer->Present(); // This call is synchronized to the display frame rate.
}

Thank you.


texts: FPS-like mouse-look camera WinAPI problem

texts:
I have a problem with implementing mouse-look camera movement, like in FPS games. For me common solution is:

Process WM_MOUSEMOVE event in WndProc
Calculate delta movement from the window's center using event's lParam
Rotate camera
Return cursor back to window's center using SetCursorPos

The problem is when SetCursorPos is called, another WM_MOUSEMOVE event is being fired. So camera rotates back.

What is the common way to create such type of camera on Windows platform (using WinAPI)?

I know that in WM_MOSEMOVE I can check is mouse.x == windowCenter.x and if it is - do nothing, but it's a hack from my point of view. Is there any "non-hacky" way to achieve the goal?


texts: How to iterate through a list of enemies and display results?

texts:
I'm making an turnbased RPG and I wanted to add a traditional multiple enemy system where a user could attack different enemies when it's there turn. I started by making a list of everybody who is going to attack and having that as the turn order. My question is how do I go through that list, and for every enemy that attacks display the damage they did and wait for the user input to continue to the next enemy.

Getting it to process all the attacks is easy, but a computer will do it in milliseconds and I need it to wait for the user input to continue.

I have started the following code:

for (int i = 0; i < turnOrder.Count; i++)
{
     if (turnOrder[i].isMonster)
     {
          ProcessEnemyChoice(enemyToAttack);
     }
     else if (turnOrder[i].isMonster == false)
     {
          ProcessUserChoice(enemyToAttack);
     }
     //enemyToAttack is assigned as a the enemy the user selected
}

I tried a do-while loop but that stopped my program from doing any updating, which makes sense. I'm at a loss here and any input from the geniuses here would be much appreciated.


texts: Command Ordering Architecture of Dwarf Fortress

texts:
What is the most elegant way to implement a command ordering system for AI? for example in dwarf fortress when you mark a forested area for wood cutting, the dwarfs then would do the following sequence:

Go to the tree
Chop the tree
Deliver wood to the stockpile
Go to another tree
and so on..

I already have a stack command working no. 1 which goes from idle state to reaching the destination tile of the tree.

What I'm afraid of is how this would get messy when I create more orders like this:

Build a house

Go to stockpile
bring wood to construction area
go back to stockpile
Bring stone to construction area
animate building sprite

Planting

Go to stockpile
bring seed to farm plot

Brewing

Go to stockpile
Bring plant to still
animate brewing sprite

So my question is, how do I implement a command ordering system like dwarf fortress and avoiding spaghetti code at the same time? are there any data structures that I need to study? Do I need to put the command sequence on a separate xml file?


texts:
I have an aircraft that is controlled by player and i need to predict it's position at needed time. It's not a problem if the plane is just moving straight but most of the time aircraft is maneuring. So i came up with an aproximation that aircraft movement can be described as a helix.

So i have a point A and linear velocity V_1 that aircraft had at a time of t_1. Point B and linear velocity V_2 that aircraft had at a time of t_2. In that approximation we may assume that |V_1| equals |V_2| so it will be a perfect helix. And i need to find a point C in that aircraft will be at a time of t_3.


texts: iPhone image asset recommended resolution/dpi/format

texts:
I'm learning iPhone development and a friend will be doing the graphics/animation. I'll be using cocos2d most likely (if that matters).

My friend wants to get started on the graphics, and I don't know what image resolution or dpi or formats are recommended.

This probably depends on if something is a background vs. a small character.

Also, I know I read something about using @2x in image file names to support high res iphone screens. Does cocos2d prefer a different way? Or is this not something to worry about at this point?

What should I know before they start working on the graphics?


texts: How do I get the size of a Plane in pixels and set it multiplied by some factor to be the size of a Sphere?

texts:
I am doing an attempt to make a 3D snake game, as an experiment but I am still a beginner. I have a Sphere that I wish to dynamically resize to be, let's say, the 20th part of the width of this Plane. How can I do this? I thought to find the size of the Plane first. I also thought to use Screen.width and Screen.height because in my actual project the Plane is almost the size of the screen, but from what I found the Transform class does not have a way to resize it to a specific dimension in pixels.

Using the code below I do not get this work, but I also see that the Sphere becomes a black circle because of the only instruction in the Start method.

Existing code

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

// Attached to the Plane
public class SphereResizer : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // what should I put here?
        GameObject.Find("Sphere").transform.localScale = new Vector3(1f, 1f);
    }

    // Update is called once per frame
    void Update()
    {
    }
}

Screenshots

Download the example

Here is the GitHub repository.

Thank you.


texts: Bullet physics weird behavior. Jittering and drifting with btBoxShape

texts:
I'm dropping a simple box onto a plane from 100 units and my solution using Bullet Physics is giving me some weird behavior. The dimensions of the box are {2, 4, 1}.

When the box hits the ground it jiggles up and down, drifts off to the side, and finally settles by sinking 1.5 units into the ground.

When I reduce the fall height to about 5 units the box doesn't sink into the ground, and the sideways drift is less pronounced.

When I declare a btSphereShape instead of a btBoxShape the problems go away. It should be noted that I'm developing for iOS with Objective-C file that interphases my code with Bullet.

Here's my code:

- (void)setUpPhysicsWorld { //This sets up the physics world and plane shape:

    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);
    broadphase = new btDbvtBroadphase();
    solver = new btSequentialImpulseConstraintSolver;
    dynamicWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);

    btTransform t;
    t.setIdentity();
    t.setOrigin(btVector3(0, 0, 0));
    btStaticPlaneShape *planeShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);
    btMotionState *motion = new btDefaultMotionState(t);
    btRigidBody::btRigidBodyConstructionInfo info(0.0, motion, planeShape);
    btRigidBody *planeRigidBody = new btRigidBody(info);
    dynamicWorld->addRigidBody(planeRigidBody);
    [self addBlock];

}

- (void)addBlock {

    btTransform t;
    t.setIdentity();
    t.setOrigin(btVector3(0, 5, 0));

    /* Actual declaration of the box shape. For some reason, when I change this
    to a btSphereShape, all the problems go away. */
    btBoxShape *boxShape = new btBoxShape(btVector3(1, 2, 0.5));
    btVector3 inertia(0, 0, 0);
    boxShape->calculateLocalInertia(1.0, inertia);

    btMotionState *motion = new btDefaultMotionState(t);
    btRigidBody::btRigidBodyConstructionInfo info(1.0, motion, boxShape, inertia);
    blockRigidBody = new btRigidBody(info);
    dynamicWorld->addRigidBody(blockRigidBody);

}

- (GLKVector3)getBLockLocation {

    dynamicWorld->stepSimulation(1/60.f, 10, 1/300.0);

    btTransform trans;
    blockRigidBody->getMotionState()->getWorldTransform(trans);

    return GLKVector3Make(trans.getOrigin().getX(), trans.getOrigin().getY(), trans.getOrigin().getZ());

}

Can anyone tell me what's wrong here?


texts: How to handle game states for a single-player / multiplayer game?

texts:
I'm developing a little simon-like game and I'd like to know what the best approach is when it comes down to game states.

What would be the best approach?

Creating different states/screens for 1-player and 2-player game sessions.
Creating just one state/screen with validation from a variable that holds the selection made by the player on the title screen.


texts: Different methods of item implementation - what are the differences?

texts:
More often that not, when I see how item systems have been implemented in games, the items are retrieved using either a string or ID. Eg, GetItem("Sword") or GetItem(ID.Sword). Is there some advantage to this method that I am missing?

When I have made item systems in my games, I create a class for the item and get a new one that way - eg, new Item(Sword). At times I have also stored the items in a list of some kind, and retrieved them that way, eg GetItem(Sword).

So my question is - why do most of the systems I see use a name tag or id system? What's the problem with getting them directly by reference?


texts: Godot _on_Area2D_area_entered not detecting

texts:
In my Scene I have a Node2D. I then Instanced the Player and Area2D nodes. The Area2D has a signal pointing to itself that prints test when run.

Here is the Code For the Area2D. Nothing happens when an object enters the Area2D.

extends Area2D

# Declare member variables here. Examples:
# var a = 2
# var b = "text"

# Called when the node enters the scene tree for the first time.
func _ready():
    pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#   pass

func _on_Area2D_area_entered(area):
    print('test')

Level Scene

Player

Area 2D

Google Drive Link to Project:
https://drive.google.com/drive/folders/1OG3BBqKJzC3Je_r5eQdqiFUp7PzzBmt1?usp=sharing


texts: Determine whether an object is 'visible' at a given distance automatically?

texts:
I am creating an environment using procedural content. To optimise performance, I am batching small meshes ahead of time. For efficiency's sake, I don't want to batch objects that make only an insignificant contribution to the final frame.

My question is, how should I determine this? Is there a commonly used or provably 'correct' algorithm?

I was thinking of something like: calculate the size of the bounding box on the final frame based on the camera parameters and see if its below a certain threshold.

Is there a better one?

(PS. This is not premature optimisation - currently my batches go well over the 65k VBO limit - not batching small meshes may save a number of draw calls. Also to be clear, I am not asking about occlusion, I have a number of small highly detailed objects in a scene so large than some will simply not be noticeable if they are far enough away and can be safely culled.)


texts: Stopping the texture2D from stretching in RawImage

texts: I am working with a RawImage texture which is fully stretched, filling up the entire scene. I am using some code to download images from website and then show them on the RawImage, the code is simple, I use WWW to start a download, use WWW.texture as the Image I want to show in RawImage, I do RawImage.texture = WWW.texture; and then I get the image but the Image is getting scrteched, I don't want to stretch the image but just fill instead, Just like a windows Wallpaper setting. Not to stretch or tile the image but to just fill it. I tried an approach to rotate the image via code but that still leaves some stretching in the image, if I use a portrait image( height is greater than width) I rotate the image from showing in landscape mode(which you can imagine, stretches the image a lot) to portrait mode by using some pixel conversion code, nothing special. Some images are displayed ok, because they fit the native size of the scene but for some stretching occurs. Is it possible to completely remove this stretching? I am surprised Unity doesn't have an option for changing how a texture can be displayed in RawImage. Maybe I am missing something,


texts:
As I'm developing a RTS game set during the Napoleonic Campaign, I've got a question about the best method to implement 'bad aim' for the AI, as the accuracy of muskets were quite terrible back then.

Currently, in my GDD, the accuracy is calculated based on: stamina, dexterity, weapon accuracy and range. But this will result in calculating the chances of a hit in a Pen-and-Paper like style. If it fails the unit will shoot somewhere else (threshold around the target), as I want to have some visible tracer for optical reasons (even though this isn't historical accurate).

Is this method okay?

Because of this the damage is calculated instantly and prevent me theoretically from implementing a first person option for the player, as this would need a second aim&shoot calculation script.

What would be another solution for this?


texts: How can I switch between two cameras with fading in/out when switching?

texts:
The first script is the way I'm using now to switch between cameras.

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

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;
    [HideInInspector]
    public Vector3 currentCameraOriginalPosition, currentCameraPosition;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;

    private int currentCamera = 0;

    void Start()
    {
        cameras = Camera.allCameras;
        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            Debug.LogError("Need more then 1 camera for switching..");
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
        currentCameraOriginalPosition = originalPosition[0];
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera].enabled = true;
            currentCameraName = cameras[currentCamera].name;

            currentCameraOriginalPosition = originalPosition[currentCamera];
        }
        lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
        currentCameraPosition = lastCameraPosition[currentCamera];
    }
}

And this is a script for starting a new game:

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

public class NewGame : MonoBehaviour
{
    public void RestartGame()
    {

    }
}

Both scripts attached to the same GameObject.
I'm calling the RestartGame method from On Click in the inspector of a button I have in the main menu.

Now in the SwitchCameras script I'm using the G key to switch between the cameras.

But now I want to do that when a new game start to fade in/out between two cameras inside the RestartGame method.
I want to call some method from the SwitchCameras script that will gade in/out between two cameras.

The idea is when starting a new game or resuming a game that the first camera will fade out slowly, fade out I mean will be enabled false slowly and then near the end to enabled true the second camera slowly.

Like switching between the two cameras but slowly.

Should i use startcoroutine ?


texts: Player appears in front of objects even if it's in the background

texts:
I have a player in Z=0 and a fence object that I want it to be in from of the player so I set it to Z=1, it's a 2D game but in the 3D view I can see that the fence is actually in front of the player but in the 2D view the player is displayed in front.

Here are a couple of screenshots.

3D view, fence in front of player:

2D view, player in front of fence:

Any idea how to fix this?


texts: Why does scissor test happen after fragment shading?

texts:
In OpenGL why is scissor test performed after shading. Wouldn't be more efficient to do the discarding before shading?

Reference pipeline overview, the scissor test is inside the Fragment Processing stage.


texts: Make UI Button Image Size Independent of Screen size Unity

texts:
I have two UI Buttons with image sprites in Panel (inside canvas). I have set their sizes to 40 in the inspector. If I run game in maximize mode, buttons retain constant assigned size of the inspector, instead of adjusting themselves with screen size. I have already added Canvas Scalar component with value Scale with Screen Size. Text fonts are able to adjust with screen size present in same canvas, but button with image does not.

Any guide on this? Thanks.


texts: I am creating my first game, I'm using Blender to create character models, is there any tutorial or guide to tell me what steps to convert a model into something animated and usable in XNA?


texts: Navigate UI with Dpad from Xbox controller on Mac [Unity]?

texts:
So, according to some documentation I found, the Xbox controller on Mac does not return Dpad presses as vertical/horizontal axes:

As you can see, the Dpad is only recognized as buttons 5, 6, 7, and 8, and not as horizontal/vertical axes. For my character's movement, I just created code that returns 1 or -1 for axis depending on the button pressed. It works perfectly fine. But then I found another problem: UI navigation.

I can't navigate my menus with the Dpad on Mac because the the EventSystem is expecting navigation via horizontal/vertical axes, which the Dpad is not providing.

Is there any way I can turn these Dpad button presses into real horizontal/vertical axes in Unity's Input system? Or is there something else I can do to make UI navigation happen on a Mac, with the Dpad?


texts:
I want to generate a competitive game like Age of Empires where each player has access to a variety of units, and each player can be distinguished by a color in each unit

And instead of sprites create 8 different colors, would have only one, with a mark where that color is changed, for example:

How do I change color of one part of sprite in Game Maker?


texts: Passing variables down the pipeline glsl

texts:
I am sorry to post a question that may be easily tested, but I don't have an OGL4+ hardware at the moment and I have to make some design decision beforehand so I wanted a clear scenario.

Looking at various tutorial that involve tessellation shaders, each single parameter that I want to send from the texture shader to the fragment shader are before passed through tessellation shaders as well (as they always needed in the case I saw).
If I have a variable that I want to send from vertex shader to the fragment one, but that's not needed by TCS and TES, can I just do something like

//// Vertex shader

out vec3 foo;

// Ignore foo in tessellation control and eval shader

//// Fragment shader
in vec3 foo;

or I have to pass foo through the tessellation shaders as well?
 I always understood the out variables are just being passed to the next stage, but what if the variable is not "picked" until another non-consecutive stage?

Thank you!


texts:
I have an orthographic projection and I try to unproject a point from screen space.

Following are the view and projection matrices:

var w2 = ScreenWidthInPixels/2;
var h2 = ScreenHeightInPixels/2;

view  = Matrix.LookAtLH(new Vector3(0, 0, -1), new Vector3(0, 0, 0),
                        Vector3.UnitY);
proj  = Matrix.OrthoOffCenterLH(-w2, w2, -h2, h2, 0.1f, 10f);

Here is how I unproject a Point p, the point is given in screen pixels:

var m = Vector3.Unproject(p, 0, 0, ScreenWidthInPixels, ScreenHeightInPixels,
                  0.1f, 10f, // znear and zfar
                  view *proj);

My code doesn't work, the matrix m contains only Nan.
When I try to invert view * proj I get back a Matrix with only zeros.

So I suspect my problem has something to do with the orthographic projection matrix.

Here are my questions:

Could the problem be caused by an underflow due to the large values in the OrthoOffCenterLH projection?
What parameters do I have to pass for x,y,width,height in Unproject(...)?
What significance has the minZ and maxZ parameter in Unproject(...)?
Does it matter what I pass for p.Z in Unproject(...)?


texts: How can I find all connected objects of the same type recursively?

texts:
In my game, when a user selects an object of some type, I'd like to search for all other objects of the same type that are connected to that first one.

For example, if the user selects a object of type 2, I want to check the object next to that one to see if it is also of type 2 and so on in all directions (up, down, left and right, et cetera) until there are no more objects of that type connected.

Does anyone know how I could do something like this? You can assume I have access to the set of connections from any given object.


texts:
I am working on libgdx.I am using this example https://github.com/oakes/libgdx-examples/tree/master/SuperKoalio/core/src/net/sekao/superkoalio to create a game.

I want to add controls on the screen, so that user can move left,right,up using the buttons.I used this "Controller" class https://github.com/BrentAureli/ControllerDemo/tree/master/core/src/com/brentaureli/overlaydemo

But I am not able to see any controls on the screen.Can any one please provide me solution to fix this.


texts: Resizing a dynamically resizable widget with a fixed aspect ratio?

texts:
I've been trying to figure this out for hours. It is a bit tricky to explain but I'll try to explain it.
I'm making a game where I have a Window with 3 panels in it. The 3 panels must always be squares (width same as height). I can figure out the height of the frame to satisfy this constraint given the width.
The tricky part is, I have a table in the game. The table is in the center of the screen. The table's size is proportional to the height of the OS Game Window. This means when the game is resized on the width, the table does not get any smaller and thus the amount of room available to the Window decreases. The window will appear at the bottom left corner.
The Window needs to be as big as possible without touching the table. The distance from the top left of the window to the edge of the Game Window must be the same as the distance from the Top Right of the Window to the edge of the table and is the same distance as the bottom of the OS Game Window to the bottom of the Window.
Here is an example:

In this example, you can see the edge of the table to the right. You can also see the Window with 3 frames and how the distances between the corners are the same (or as close as I could get it).
Given that I know the size of the table and its location, and the width and height of the OS Window how could I get it to do this? I do not necessarily need code or anything, but I'm more likely looking for the main idea on how I could do this mathematically. As you can see in the image, about 15% of the space is padding, I need to be able to have padding so that it does not consume the maximum area.
Thanks


texts: How do I shoot bullets towards the mouse in a top down shooter?

texts: I have a formula for pointing my main character of the game towards the mouse, and it gets the angle he needs to be turned to point towards the mouse. But how do I get the bullets from the gun to use the angle produced and shoot a bullet towards the mouse.


texts: How do you determine the amount of moves/turns/lives that should be given to a player?

texts:
Let's take Candy Crush for example. The player is given 50 turns to complete a certain level.

How is such number determined? Are there educated ways to reach such numbers?

I also presume that these numbers are refined through game updates, but there must be a reasonable starting point to keep the player interested enough without making it extremely difficult or too easy.

Note: I'm only using Candy Crush as an example. I'm looking for general answers to this issue.


texts: How to draw Isometric game Back to front

texts: What is the for loop or algorytm for a 2D array of tiles that I would render the tiles back to front like this:


texts: How to organize level blocks in an Infinite runner

texts:
I'm working on an Infinite Runner game. I have created many level blocks(sections) with different obstacles and pick-ups for the player. They are positioned and placed manually, in such a way, to give the player a challenge. I thought that making every block a prefab and placing every obstacle and coin as a child of that prefab is going to be easier for me..because the player is going to run and these block prefabs are going to be randomly spawned in front of him and then destroyed after the player gets past them. It worked well.

Then I wanted to make a change on my coins. So naturally I took the coin prefab, made the changes, and applied them hoping that the change is going to take effect on all my blocks... Well..it didn't. Then I found out that nested prefabs don't work in Unity, so now I have to reorganize everything again?

How do I create organized level blocks, and then make them randomly spawn in front of the player? Is there any other option besides prefabs? Don't tell me I have to use a script for every block?

Think about Banana Kong, Temple Run, Subway Surfers. The levels seem random, but it's an organized randomness with certain portions of the level repeating themselves. That's what I'm trying to do, and I don't know how to organize it...


texts: How do programming skills aid a game designer

texts: So many game designers are programmers as well nowadays. Is it so extremelly helpful for a game designer to have programming skills and in which ways programming skills aid a game designer?


texts: Can't refer mesh size after using .BakeMesh() in Unity

texts:
I can't figure out how to refer to the size of a particular mesh.

The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be.

This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size.

Here the plot thickens. The mesh's size just comes back at 0, 0, 0.
My attempts at getting the size of the object are as follows:

objectToMeasure.GetComponent<Renderer>().bounds.size;

objectToMeasure.GetComponent<MeshFilter>().mesh.bounds.size

objectToMeasure.GetComponent<MeshFilter>().sharedMesh.bounds.size;

Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world?

I feel sure that
objectToMeasure.GetComponent().mesh.bounds.size;
should be right, since the script I use to bake to the mesh is:
meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh);

I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.


texts: Scale a normalized 2D vector always to the same length

texts:
For any normalized 2D vector, except for ( 0, 0 ), how would I scale the vector to always be the same length?

For example:

int length = 10;

vector v = vector( 0.1, 0.5 );
vector v2 = vector( 0.3, 0.8 );

// Scale v to be length of 10
// Scale v2 to be length of 10


texts: Is it sensible to run a Socket.IO setImmediate loop for each connected player?

texts:
Instead of a game loop, I want something different: My game does not have much action going on; just moving users over a tile map with correct timers in between.

Since I am using Socket.IO, I want to run a "mini game loop" inside the io.sockets.on("connected"-part of my script. I am thinking to run a setImmediate checking a few variables to know what to do with the player.

The way I understand socket.IO, it would create this setImmediate function for each client that joins the server. (Because it runs inside the "connected" event handler.)

Let's say 1000 players join the game. If what I fear is true, this approach seems bad. Have I misunderstood setImmediate?


texts: NullReferenceException in Swipe Controller Script

texts:
I am Getting a Exception in My Swipe Controller Script name Dot.Here is the Code

using UnityEngine;

 public class Dot : MonoBehaviour
 {
private Vector2 firstTouchPosition;
private Vector2 finalTouchPosition;

public float swipeAngle =0;
// Start is called before the first frame update
void Start()
{
    firstTouchPosition = new Vector2(0,0);
    finalTouchPosition = new Vector2(0,0);
}

// Update is called once per frame
void Update()
{

}

 void OnMouseDown()
{
    firstTouchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    Debug.Log(firstTouchPosition);
}

void OnMouseUp()
{
    finalTouchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Debug.Log(finalTouchPosition);
    CalculateAngle();
}

void CalculateAngle()
{
    swipeAngle = Mathf.Atan2(finalTouchPosition.y - firstTouchPosition.y, finalTouchPosition.x - firstTouchPosition.x)*180/Mathf.PI;
    Debug.Log(swipeAngle);
}  }

Please Tell ME What Im Doing Wrong.


texts: Forward Shading with multiple shadow-casting lights

texts:
I am currently thinking about how to organize shadowing and lighting.
We use forward rendering and currently, our algorithm looks like this:

collect all items that are visible in the view
for each item, collect a list of lights where the item is in the attenuation radius (each item keeps a list of lights)
determine the shadow light by the distance of the main character (only one light can currently cast shadow)
render the scene by using a constant buffer of the currently processed item to shade it (each item is rendered with a constant buffer which contains light properties. the number of lights per item is predefined so we have a Light[16] and numLights in the constant buffer)

How would I do multiple shadow-casting lights in an organisatory way?
We do not want to go the deferred way, since we dont want to limit us to GBuffers.


texts:
So I did some research and a found Box2d.  I then proceeded to download it and the testbed.  Now that i have it, I don't know how to properly use it.  I'm looking for a clear simple answer on how to use the engine.

The things I did was that I put it into a lib folder and referenced the JBox2D jar file.  After that i got stuck.  How can i use this to program games for android?

I'm very confused since Box2d was intended for C++.


texts: Allow Pushing|Boosting in free browser MMOGs?

texts:
There seems to be a set of rules (or game design criteria) common to free MMOGs, to encourage fair competition. One such rule is that each player may have only a single account (despite the difficulty of enforcing this effectively). A related issue has recently come to my attention, where a player who does not themselves play often, instead of using their limited resources for their own gain transfers them to another, stronger player. Commonly these might include spouses or disinterested roommates or children, or friends who are no longer active in the game.

Does this advantage violate an essential aspect of the design of the game, or should it be permitted?


texts:
I have to write a game for a uni project using openGL / glut. I am just going to use a generic example code as I'm just looking for a solution to one specific problem:

Using glut, I have to call a function 'glutDisplayFunc(display);' in the main function. I am also using an IdleFunc(update). The problem is that, as described here, the 'display' function cannot pass anything. I have some structs outside my main that I wish to be initialized in the main, and be accessible by display and update. Hopefully some code will explain my problem better:

#include <gl/glut.h>

struct Player
{
GLfloat x;
GLfloat y;
GLfloat z;
int score;
...
}

//function prototypes (showing how I would normally pass the struct)
void InitPlayer         (Player &player);
void DrawPlayer         (Player &player);
void UpdatePlayer           (Player &player);

void main (int argc, char **argv)
{

    Player player;

    InitPlayer(player);

    //...
    //glut / openGL initialisation code left out
    //...

glutDisplayFunc         (display);
glutReshapeFunc         (reshape);
glutIdleFunc            (update);

glutMainLoop();

}

void display()
{
DrawPlayer(player);
}

void update ()
{
UpdatePlayer(player);
glutPostRedisplay ();
}
//end

The above code doesn't work: I hope it demonstrates what I would like to do though. Access the struct 'player' in 'display' and 'update', having the same values stored globally. How would I go about ?


texts: Blender models appear in UDK asset manager, but not in game

texts:
I am new to UDK and blender. I am using UDK3.

I have tried the following so far:

Making the mesh origin, (0,0,0)
Making the parent bone origin (0,0,0)
Parenting the root bone with the mesh

I have tried exporting in the following file formats:

*.psk
*.fbx

Both fbx and psk import into the UDK asset manager, and are viewable in the asset manager. I have also previewed my weapon Im importing against a chracter model, and it appears to be slightly too large (which is easy to fix). Many other forums mentioned for other people that the models might be displaying but be very very small.

I have tried viewing in:

3rd person
1st person (Weapon factory, and giving weapon via console command)

I have made the blender file avaliable here: http://www.fileswap.com/dl/m1BiH78Gba/

The code is just standard wizard generated code and has worked previously for other weapon models.

Any ideas or clues about how I can go about trouble shooting this would be greatly appreciated.


texts:
Note: I plan on making my own GUI system. It will be good for learning, lightweight, only have bits I need, ties in with the game, etc.

I was thinking about how to do it. The elements I mean are:

Radio buttons
Enter text here boxes
Buttons
Sliders
Checkboxes

I'm not looking as to how to make them, yet. But more of how they would go.

Idea

I would have each state that needed stuff, so almost all, have a container of Elements. Each Element is-a GUI piece.

These each have position, a graphic, etc.

The bit I get more stuck on is the logic of them.

My idea for that, to allow for modularity and simplicity was to avoid a MainMenuStartButton; a OptionsOneBackButton, etc. and instead be able to do Slider slider1; or Button start;.

Instead, each would have a boost::function to a function in a GUI namespace, such like Gui::StartButtonClick, or GUI::ColourSliderHover.

I was just wondering whether this would be exceptionally slow or not.

And for that matter, is there any easy, simple way of doing GUI for games? No Qt, wxWidgets or anything.


texts: Why should I consider using the Source Engine?

texts:
I've always been a Valve fan, but now that I have the opportuninty to choose a game engine for a project I'm not sure I want to choose the Source Engine after watching this wikipedia entry. My options essentially boiled down to an open source stack (Horde3D + Zoidcom + Spark + SFML + CEGUI, and well, not OSS but PhysX too), UDK and the Source Engine.

My question is (because I really have no experience with it) what would be the technical reasons (not license or other) for any developer to choose the Source Engine over any other open source or commercial option ?, is the Source Engine really worth it as a game development tool or has it time already passed and it is obsolete against other solutions?.

Thanks

Edit: Precised my question a little more
, I'm looking for technical reasons to choose the Source Engine.


texts:
I have a scene with 3d objects but need uGUI as background.

How can I achieve this?


texts:
I'm working with this tutorial http://www.html5rocks.com/en/tutorials/webgl/webgl_transforms/

and my result is, that the rectangle moves in the direction of it's scaling values, and also scales at the same time. So if I scale (2.0, 1.0) it moves right and stretches, but I only want to strecht/scale it. This is my vertex shader, it is nearly the same as in the tutorial (declarations omitted):

void main(void) {
vec2 scaledPosition = a_position * u_scale;

vec2 rotatedPosition = vec2(
    scaledPosition.x * u_rotation.y + scaledPosition.y * u_rotation.x,
    scaledPosition.y * u_rotation.y - scaledPosition.x * u_rotation.x);

vec2 pos = rotatedPosition + u_translation;

vec2 zeroToOne = pos / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;

v_texCoord = a_texCoord;

gl_Position = vec4(clipSpace, 0, 1);
}

What could be the mistake if it is not in the shader? Thanks in advance.


texts: Unity: Can we not change Animator State inside Update?

texts:
void Update () {

        if (goright == true) {
            rig.velocity = new Vector2 (m.movespeed, rig.velocity.y);
            m.anim.SetInteger ("State", 1);
        }

        if (goleft == true) {
            rig.velocity = new Vector2 (-m.movespeed, rig.velocity.y);
            m.anim.SetInteger ("State", 1);
        }
    }

    public void ondownMoveLeft(){

        goleft = true;
    }

    public void ondownMoveRight(){

        goright = true;
    }

    public void onupMoveLeft(){

        m.anim.SetInteger ("State", 0);
        goleft = false;
    }

    public void onupMoveRight(){

        m.anim.SetInteger ("State", 0);
        goright = false;
    }

i am using this code to move my character using UI buttons with the help of Event Triggers. i set it to change the animation from idle to running or from State 0 to 1 when the player moves and it does works that way but the problem is once it goes into State 1 it never comes back to State 0 but it should since i am setting the State back to 0 when the OnPointerUp trigger gets activated. am i missing something?

OnPointerDown is calling its respective ondown method and OnPointerUp is calling its respective onup method. for eg, when you press the left button it calls OnPointerDown which is set to call the method ondownMoveLeft.

i also checked with Debug.Log and everything is being executed but still the animation State is not changing.


texts: How are Roguelike/Bullet Hell mechanics stored in Unity?

texts:
I'm going to be creating a roguelike bullet hell game wherein the play will be a bullet hell game, but you will be traveling between "rooms" wherein the action takes place. The "rooms" will be randomly generated like in roguelikes such as The Binding of Isaac, but with bullet hell play similar to Touhou or Batsugun, with a possible twist. It will be similar to Enter the Gungeon, but there will be some differences.

I'd like to know how Unity will deal with storing possibly thousands of different "rooms" and generating these each time, along with the enemies and bullets these enemies will begin to shoot after you enter the room. Only one room will be visible at a time.

How would Unity deal with mapping possibly thousands of rooms, and will it be able to store this while generating bullet patterns? I know that in classic bullet hell arcade games, when there were many bullets on the screen, the game tended to slow down because of hardware limitations.


texts: Why do I get odd color effects in smooth transitions with OpenGL?

texts: I am making a planet generator, and when I go too close to the planet, the smoothly colored surface has striations. Very visible striations, as seen in the attached image. The color transition is supposed to be completely smooth, set with a double precision floating point (which, AFAIK, is actually overkill), but no matter how I generate it, the striations appear. I understand that there are only so many nuances of grey or other colors to go around, but if I place a grey shade of 140 (in a 0-255 range) next to one with 141 in any graphics program (e.g. GIMP), they are indistinguishable, meaning there should be no striation, as they would 'melt together'. I checked polygon topology, that's not it (if I set the color nuances to rotate, the striations do not follow polygons at all). I've tried upping the color depth to 32 bit, with no change. I even tried manually casting the resulting values as 'float' for the glColor3f assignment! Nothing works, the striations remain! Is there a limit on the nuances OpenGL can give to colors? Can I remove that? Or is there another explanation?


texts: Normals in my skinned model are not animated

texts:
I have a blender skinned mode with animation. Normals look like they are messed up. This is how it looks in Unity3D before and after animation.

As you can see, my model should be lit up just like the cube next to it. When I apply Armature modifier in blender, my model looses animation and its locked in particular position, but the light on that model works.

My question is: The normals are set as they would be for a static model, not for a animation. Why are normals not animated ?


texts:
(I am specifically asking for Android)

If you look at Angry Birds (and in fact many other games), you can already see a lot of animations & effects going in the main menu and in other places even before starting to play. I assume they are done with OpenGL, more precisely a FrameLayout is used and inside it a GLSurfaceView is somewhere at the bottom of the hierarchy; above the GLSurfaceView you have regular Android buttons and texts.

Is this how it's done*? Also would you reuse the same GLSurfaceView when running the actual game or should another one be created?

*I am aware an alternative approach would be to make absolutely everything in OpenGL. Of these two I prefer the FrameLayout one, but I don't know whether other developers agree.


texts: how to follow(center) a box inside canvas element

texts: If inside a canvas I draw a box, and the I add arrows to move it, the box will eventually be out of my reach since it goes out the border and I cant see it. How could I follow the box so that it is always in the center?


texts: Collision response using the Minimum Translation Vector

texts:
I am trying to use the Minimum Translation Vector (MTV) returned from the SAT algorithm for simple collision response. Please see the example below.

By separating the colliding boxes by moving the black box along the MTV, the box is now colliding with the other green box below. Moving the black box along the MTV for the collision with this new box then brings the box back to colliding with the first box, and an infinite cycle of trying to separate the boxes begins.
Am I missing something, or is collision response not possible using the MTV?


texts: How can I utilize external libraries within an entity system?

texts:
I'm implementing an entity system for educational purposes.  I wanted to focus on the system itself and don't know much about rendering and physics, so I'm using external libraries for those tasks.

These libraries come with pre-defined classes for their objects (sprites, bodies, etc.)  These do not fit into my entity system easily.

How can I utilize existing libraries and classes within an entity system?


texts: Is it a good option to simultaneously work on a game and a game engine?

texts:
I'm considering this, now I work on 3d game but I want also to make in slow tempo, iteratively a game engine is it a good choice?
The game what I working on is with non custom engine (Unity, Unreal Engine 4 - I not yet selected, switching from engine to engine)
and also I want to develop a custom 3d engine but this engine will not be heavy but lightweight so with selected features. So I'm not talking about making Unity like engine but still 3D thank you for answer :)
And this engine will contain:

c#
opengl
existing physics engine (Bullet or sth)
...

what I not considering:

editor
multiplayer
characters

so just API
Additionally I have linear algebra background but no experience with shaders
edit: currently I want to make game in existing game engine
but in future I want to migrate with game to custom game engine


texts: Understanding the Entity-Component Model

texts:
Possible Duplicate:
  Role of an entity state in a component based system?

So, I've heard a bit about a model of game programming that involves creating entities and then attaching different components to them to change their behaviour. So, an enemy entity might have attached components of AI, collision physics, etc. This seems like an excellent way to solve a lot of the problems in creating an engine, but I don't really have a precise idea of what exactly an entity or component is.

So my question then: what exactly should an entity object encapsulate? How would I go about attaching components to it?


texts: Fixed timestep game loop, why interpolation

texts:
This is a very standard way of doing a fixed timestep game loop, where you just accumulate time from the previous frame and consume it in discrete steps with the physics engine:
    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

A lot of articles suggest that with the residual lag we should do an interpolation between the previous update and the current one, BUT it does not make any sense to me!
If you have residual lag it means that you still have some time to catch and you should EXTRAPOLATE the current state. Why would you ever do an interpolation with the previous state?


texts: Variable from class doesn't show in editor

texts: this may be another beginner question. I have a simple data holding script and want to pass one variable from it as parameter to a function. But in the editor it only shows me the script name, not the option of any variable. What attribute or change do I need to make to make the variable visible for selection? (Passing the whole object works, but I don't like the parsing of the object inside the called method and would just to pass the parameter directly) Picture for easier understanding.


texts: Why do I see "<" and ">" in Unity C# code?

texts:
I copied Unity code from a website and now it contains stuff like &amp;lt; T &amp;gt; which my IDE flags as an error.

It looks like the intended text has been corrupted somehow. What is this supposed to be, and how can I correct it?

public class Tree&lt;T&gt;
{
    public T Data { get; set; }
    public IEnumerable&lt;Tree&lt;T&gt;&gt; Childs { get; set; }
    public bool Opened { get; set; }

    public Tree()
    {
        Childs = Enumerable.Empty&lt;Tree&lt;T&gt;&gt;();
        Opened = true;
    }
}


texts:
I am currently reading a book named "3D Graphics with XNA Game Studio 4.0" by Sean James and have some questions to ask :

If i create a effect parameter named lets say SpecularPower and have in my effect a variable named SpecularPower , if i do something like

  effect.Parameters["SpecularPower"].SetValue(3)

That wil change the SpecularPower variable in my effect ?

And a second question, not regarding the book :
If i have a spaceship and i've created a "boost" functionality that speeds up my spaceship, what effects should i implement to create the impresion oh high speed ? I was thinking of making everything except my spaceship blurry but i think there would be something missing . Any ideas ?

Regards,
Alex Badescu


texts:
In my almost finished game I want to set a new screen on game over. I got my game over method:

    private void gameOver(Label score) {
    for (Body body : worldBodies) {
        world.destroyBody(body);
        dispose();
        ((Game) Gdx.app.getApplicationListener()).setScreen(new GameOver());
    }
}

Whenever the method gets called the screen freezes for a second and the game crashes with this statement:

09-02 22:04:34.036      391-425/com.joelbrun.jetskirider.android A/libc﹕ Fatal signal 11 (SIGSEGV), code 1, fault addr 0x8 in tid 425 (GLThread 29501)


texts: How can I convert screen space to GUI Space/View Space?

texts: Is there any way available to convert screen space into view space as like in the following figure:


texts: How does ESRB content rating work for games with DLC?

texts: Lets say you have a game rated "Teen" by the ESRB, but later down the line, you release a DLC that would push the game's rating to "Mature". Are the two ratings kept separate for the base game and the DLC or will the base game be "upgraded" to the higher DLC rating?


texts:
So I've been trying to make a pretty accurate clone of the good old Pokemon Yellow for quite some time now and one puzzling but nonetheless subtle mechanic has puzzled me. As you can see in the uploaded image there is a certain colour manipulation done in two stages after entering a wrap to another game location (such as stairs or entering a building).

One easy (and sloppy) way of achieving this and the one I have been using so far is to make three copies of each image rendered on the screen all of them with their colours adjusted accordingly to match each stage of the transition. Of course after a while this becomes tremendously time consuming.

So my question is does anyone know any better way of achieving this colour manipulation effect using java?

Thanks in advance,

Alex


texts: Need help with collision detection/resolution in a 2D simulation of 'worm-like' creatures

texts:
(originally posted this on regular stack overflow, somebody pointed this forum out :-) )

Hi there,

I'm implementing a physics engine for the simulation of worm-like creatures. Problem is, is that they're able to swim over each other and occupy the same point in space. So you have some idea of the environment, I provide a video here: http://www.box.net/shared/mlddkslszbxd59cfdhpc

So what I need to do is incorporate a collision detection and resolution algorithm that would overcome this. For the detection part, I've been utilising bounding circles; each worm is given an outer coarse circle which if crossed then triggers detection around smaller fine grain detection circles as placed around each body segment.

That bit is relatively easy. The more difficult bit is to decide what to do given a collision. My problem is how to derive and correctly set the velocities and forces of the point masses after a collision has taken place.

Just in case its not entirely obvious, each worm is made out of springs and point masses. Each body segment of a worm assumes a rectangular shape at rest with 4 point masses and 6 springs (since there are also two diagonal springs).

Now it was suggested over on regular stack overflow that I implement an elastic collision by summing the momentum of worm A and the momentum of worm B (when they collide). The way I do this is on a body segment by body segment basis: if two body segments from two different worms are close enough (i.e., colliding), then I sum the momentum of each and divide the result by 2. This yields a new velocity value which I then apply to the velocity of each body segment. This is meant to have the effect of 'springing' the colliding body segments away from each other.

However, I don't think I'm implementing it correctly. The issues are: when worm A hits worm B, if they are both swimming strongly enough, they both still swim through each other albeit at a slower pace. An example of this is shown in this video here: http://www.box.net/shared/sankz3i7xeenilhzhqfo

The second issue is that if two worms are within collision range and worm A swims away from worm B, then worm A proceeds to pull worm B along with it although at a slower speed than normal un-hindered swimming.

I'm really not sure how to go about this. I've read about requiring the setting of angular velocity for two colliding bodies but I'm not sure whether this only applies to solid bodies or not..An elastic collision seems the most sensible given that I'm using a spring based model.

If anyone can help, I'd greatly appreciate it

Thanks,

Ben.


texts: Using DirectWrite to write text on a IDirect3DTexture9

texts:
I'm trying to write text using the DirectWrite API on a IDirect3DTexture9. I've heard that people were capable of doing this but I do not see directly how I can glue these two APIs together.

It seems I need a IDXGISurface to create a valid ID2D1RenderTarget (with which I can draw the text). I can get this by creating a surface for the Window. But I think the idea is that I use the IDirect3DTexture9 as a surface for the render target so that I can use whatever is drawn on it in my application.

I can get the underlying IDirect3DSurface9 from the IDrect3DTexture9 but then I have to convert it somehow to a IDXGISurface and this is where I'm stuck. Does anybody have a clue?


texts: Civilization 6 add City States in World Builder

texts:
There are instructions to access the Civ 6 Worldbuilder in civfanatics forums.

The TZ mod method allows starting with a custom map, but there are no generated city states.

How can I add city states to the map / mod so the game does not crash on the first turn?


texts: Canvas slowly degrades in performance after a while

texts:
I was creating a simple game and was shocked to see how the performance started to degrade. It never happened to me before, most probably because I use images and not the context drawings. So I used this function and the whole game becomes so slow, it just cannot be played after 30 seconds.

Office.prototype.draw = function(){
 for(var i = 0; i < this.tables.length; i++){
  for(var j = 0; j < this.tables[i].length; j++){
   Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 250, 170, 20);
   Canvas2D.ctx.fillStyle = 'green';
   Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 250,
    this.moneyBar[(i*4)+j], 20);

   // Draw the experience bar.
   Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 270, 170, 20);
   Canvas2D.ctx.fillStyle = 'yellow';
   Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 270,
    this.expBar[(i*4)+j], 20);

   // Draw the tables.
   Canvas2D.drawImage(sprites.items[0], new Vector2(
    (250 * j) + 50, (250 * i) + 200));
  }
 }
}

So as you can tell from the code, there is the multidimensional array table which has bars on top displaying moneyBar and expBar.
If I am to use Canvas2D.ctx.stroke() inside the for loop, the game performance drops right away. Outside of the loop, it keeps up a bit, then it degrades. If I don't use stroke at all, works better, but degrades anyway. So I am really confused as to why this degrades so fast. Also am using requestAnimationFrame and have used the same engine in previous games and performance never degraded.

If I was to remove fillStyle, keeps up 3-4 seconds more.
There are 8 tables in all, which means the for loops run 8 times per draw.

Vector2 function.

function Vector2(x, y) {
    this.x = typeof x !== 'undefined' ? x : 0;
    this.y = typeof y !== 'undefined' ? y : 0;
}


texts: Don't message systems slow down game engines?

texts:
I am wondering, aren´t messaging systems slowing the speed of engines down? I mean, lets say that I want to zoom in my camera, without messaging I would do something like:

_camera->zoomIn(0.005f);

But with messaging, I have to broadcast the message (to the bus for example)

Data data;
data.float = 0.005f;
MessageBus::sendMessage(CAMERA_ZOOM_IN,&data);

Then iterate through all systems (all systems that can possibly handle the message) and at the end, when it arrives to my camera system, I have a handling function that calls proper method based on the message type.

eventFunctions[CAMERA_ZOOM_IN](data);

That means it needs some additional time to "do stuff" and also harder implementation. (imagine for different data types I also need some static casts etc.)

So, will it affect the actual speed of my engine?


texts: With 2 superposed cameras at different depths and switching their culling masks between layers to implement object-selective antialising:

texts:
We superposed two cameras, one of which uses AA as post-processing effect (AA filtering is cancelled). The camera with the AA effect has depth 0 and the camera with no effect has depth 1 as can be seen in the 5th and 6th Picture. The objects seen on the left are in layer 1 and the ones on the right are in layer 2. We then wrote a script that switches the culling masks of the cameras between the two layers at the push  of buttons 1 and 2 respectively,  and accomplishes object-selective antialiasing as seen in the first the three pictures. (The way two cameras separately switch culling masks between layers is illustrated in pictures 7,8 & 9.)

HOWEVER, after making the environment 3D (see pictures 1-4), by parenting the 2 cameras under First-Person Controller, we started moving around in the environment and stumbled upon a big issue: When we look at the objects from such an angle  as in the 4th Picture and we want to apply antialiasing to the first object (object on the left) which stands closer to our cameras now, the culling mask of 1st camera which is at depth 0, has to be switched to that object’s layer while the second object has to be in the culling mask of the 2nd camera at depth 1. And since the two image outputs of two superposed cameras are laid on top of one another; we obtain the erroneous/unrealistic result of the object farther in the back appearing closer to the camera than the front object (see 4th Picture).

We already tried switching depths of cameras so that the 1st camera –with AA- now has depth 1 and the second has depth 0; BUT the camera with the AA effect Works in such a way that it applies the AA effect to its full view. So; the camera with the AA effect always has to remain at the lowest depth and the layer of the object to be antialiased has to be then assigned to the culling mask of the AA camera; otherwise all objects in the AA camera’s view (the two cubes in our case) become antialised, which we don’t want.
So; how can we resolve this? The pictures are below and in the comments since each post can have 2 pics:

Pic 1. No button is pushed: Both objects seem aliased.

Pic 2. Button 1 is pushed: Left (1st) object is antialiased. 2nd object remains aliased.

Pic 3. Button 2 is pushed: Right (2nd) object is antialiased. 1st object remains aliased.

Pic 4. The problematic result in 3D, when using two superposed cameras with different depths

Pic 5. Camera 1’s properties can be seen: using AA post-processing and its depth is 0

Pic 6. Camera 2’s properties can be seen: NOT using AA post-processing and its depth is 1

Pic 7. When no button is pushed, both objects are in the culling mask of Camera 2 and are aliased

Pic 8. When pushed 1, camera 1 (bottom) shows the 1st object and camera 2 (top) shows the 2nd

Pic 9. When pushed 2, camera 1 (bottom) shows the 2nd object and camera 2 (top) shows the 1st


texts: Restricting body movement withing a specific length while dragging a gameobject in unity

texts:
private void OnMouseDrag()
{
    Vector3 screen_sp=new Vector3(Input.mousePosition.x,Input.mousePosition.y,screen_space.z);
    Vector3 cur_pos=Camera.main.ScreenToWorldPoint(screen_sp)+offset;
        if(pendulum_object.gameObject != null && pendulum_object.gameObject.rigidbody!=null)
        {
                transform.position=cur_pos;
                    Debug.Log ("Pendulum is being dragged left"+transform.position);
                    Debug.Log("Mouse position is:"+Input.mousePosition);
                    Debug.Log("Current position is:"+cur_pos);
        }
}

The problem is:The dragging of game object must be restricted to the length of string.
The pendulum is joint using hinge joint to the world.


texts: Need to programatically muffle game sounds

texts:
So I work on a multiplayer game that is set in space. There are essentially two environments for players to be in: inside a sealed space station (where there is air and thus sounds) and outside the station in the vacuum of space (where there is no air and no sound to hear).

For a while now, we've had it so that you cannot hear any of our game's sound effects while floating in a space with no air, and while that might be realistic, it's not very fun when the game is completely silent sans background music.

I'd much rather find some way to dynamically distort the sounds on the fly before they are played so that they seem to be muffled or dampened. I have no sort of background in making sounds or doing much of anything with them and all my searches have amounted to nothing; mostly finding things about sound editing programs.

The project is made in a C based language for game programming that is really obscure called Dream Maker or Byond. I can't seem to find any built-in features that are able to solve this problem for me. Any help would be much appreciated.


texts: Are there any disadvantages of using Distance Squared checks rather than Distance?

texts:
I use distance squared checks for basically all my distance (vector3 length) checking, due to the performance increase from not incurring a square root (like in plain length checks).

From the looks of it, squared distance checks work fine in every situation:

if x^2 < y^2, then x < y, even when 0 < (x or y) < 1

I am not considering situations where x or y is less than 0, as distance and distance-squared is always going to be positive.

Since this works, it looks like distance checks are never ever needed, but I have a nagging feeling that i'm missing something. Will this still hold up in accuracy-critical situations?


texts: What do you do with "Player Start" and "Pawn" objects when setting up the default VR game in Unreal?

texts:
I followed the setup tutorial provided by Unreal from here but after setting up the pawn and the VR_GameMode you don't do anything with them. They are never added to the scene or anything and the default game comes with a "Player Start."

Is the "Player Start" object supposed to be removed? If you remove that then running the VR Preview shows the game from wherever your camera is in the viewport and there is no game location. Adding the pawn to the scene doesn't seem to do anything. The final image they show doesn't have the "Player Start" object in the scene at all and they never mention it so I'm unclear about how to complete this process.

Adding the pawn to the scene seems to have no noticeable affect on how the game is run in VR Preview. What's the proper last step?

After following the instructions exactly as-is the floor is way below the current start point and modifying the Z values as instructed has no affect on the floor. Moving the "Player Start" does, but this could have been done from the very beginning without doing any of the setup with the pawn or the GameMode.


texts:
I have a triangle in 3d space and would like to create a grid over the triangle, such as in the image below.

The purpose of this is to store information about each block of the grid. In order to store this grid in a 2D array, my idea was to rotate the triangle until it is in the XY plane. After rotation the above triangle would look like the image below.

What I have tried to do is find the angle between the triangle's normal and the z-axis, then rotate each vertex by this amount.

    public double getAngle(Vector3 normal, Vector3 axis) {
        double dot = normal.dotProduct(axis);
        double angle = Math.acos(dot / (normal.getMagnitude() * axis.getMagnitude()));
        System.out.println("angle = " + Math.toDegrees(angle));
        return angle;
    }

    public static void main(String args[]) {
        Vector3 pointA = new Vector3(0,0,0);
        Vector3 pointB = new Vector3(5,5,5);
        Vector3 pointC = new Vector3(-5,5,5);
        Triangle tri = new Triangle(new Vector3[]{pointA, pointB, pointC});
        Vector3 normal = tri.normal();
        normal.normalize();
        Vector3 zAxis = new Vector3(0, 0, 1);
        Matrix4x4 rot = Matrix4x4.getRotationMatrix(0, 0, patch.getAngle(normal, zAxis));
        for(int i = 0; i < tri.vertices.length; i++) {
            tri.vertices[i] = rot.multiply(tri.vertices[i]);
        }
    }

The result of this code would be:

Triangle's normal: (0.0, -50.0, 50.0)
Normalized normal: (0.0, -0.7071067811865475, 0.7071067811865475)
Vertices after rotation:
   (0.0, 0.0, 0.0)
   (4.440892098500626E-16, 7.0710678118654755, 5.0)
   (-7.0710678118654755, 4.440892098500626E-16, 5.0)

This is not quite right, though. I am expecting all z-coordinates to be the same so that I can ignore them and store the grid in a 2d array. Is there something else I need to do to rotate the triangle appropriately, or is there a simpler way to store this grid? If needed, the code for my rotation matrix is below:

private static Matrix4x4 getRotationMatrix(double x, double y, double z, boolean inverse) {
    double sign = (inverse) ? -1 : 1;
    Matrix4x4 rotateX = new Matrix4x4(new double[][]{
            {1, 0,             0,            0},
            {0, Math.cos(sign * x), -Math.sin(sign * x), 0},
            {0, Math.sin(sign * x),  Math.cos(sign * x), 0},
            {0, 0,             0,            1}
    });
    Matrix4x4 rotateY = new Matrix4x4(new double[][]{
            { Math.cos(sign * y), 0, Math.sin(sign * y), 0},
            { 0,            1, 0,            0},
            {-Math.sin(sign * y), 0, Math.cos(sign * y), 0},
            { 0,            0, 0,            1}
    });
    Matrix4x4 rotateZ = new Matrix4x4(new double[][]{
            {Math.cos(sign * z), -Math.sin(sign * z), 0, 0},
            {Math.sin(sign * z),  Math.cos(sign * z), 0, 0},
            {0,             0,            1, 0},
            {0,             0,            0, 1}
    });
    Matrix4x4 rotation = rotateZ.multiply(rotateY).multiply(rotateX);
    return rotation;
}


texts: Figuring out if two objects overlap on screen

texts:
I want to figure out if 2 3D models overlap on screen. My general idea is:

Compute the bounding box of each model
Transform the bounding box to the View Volume using the ViewProjection matrix
Check if bounding boxes overlap in the view volume, ignoring the Z-axis

For step 1 I've used the answer to this question. But I'm having problems implementing step two.

I wrote the function below but its giving me inconsistent results. The numbers seem good for corners that fall inside the view volume (after multiplying by the ViewProjection matrix). But if an object falls off the screen the numbers seem incorrect. What am I doing wrong?

public static BoundingRectangle ProjectBoundingBox(BoundingBox box, Matrix viewProjection)
{
    var minX = float.MaxValue;
    var maxX = float.MinValue;

    var minY = float.MaxValue;
    var maxY = float.MinValue;

    var corners = box.GetCorners();

    foreach (var corner in corners)
    {
        var projectedCorner = Vector4.Transform(corner, viewProjection);
        projectedCorner /= projectedCorner.W;

        minX = Math.Min(minX, projectedCorner.X);
        maxX = Math.Max(maxX, projectedCorner.X);

        minY = Math.Min(minY, projectedCorner.Y);
        maxY = Math.Max(maxY, projectedCorner.Y);
    }

    return new BoundingRectangle(minX, maxX, minY, maxY);
}

Edit: the numbers

If you see the attached screenshot you see two semi-transparent stained glass windows.

Fully visible window:
    Bounding Box: Min( -43.62131  25.6  -10.32131 ), Max( -37.38873  34.4  -4.08873 )
    Projected Coordinates: Min(-0.7539723,-0.5401732), Max(-0.2793865, 0.27869606)

Partially visible window:
    Bounding Box: Min( -40.5142  25.6  -1.2 )  Max( -40.5  34.4  7.6 )
    Projected Coordinates: Min(-32.07214, -23.4672337), Max(47.5241241, 0.334790081)

As you can see the projected coordinates for the only partially visible window are gigantic. I would expect MaxX to be something like -0.9 and MinX maybe -5. But the numbers are way off.

The culprit seems to be some of the corners of the bounding box. For example (-40.5142  34.4  7.6) is transformed to (47.52412  -12.65482  1.539964). What is interesting here is that the W coordinate is negative and less than 1  (-0.18), while for the corners that do seem correct w is positive and larger than 1.0.

Edit #2:

Here's a second picture where I've added a visualization of the projected rectangle. On the left you see the exact scenario where it goes wrong. The right side of the rectangle for the partially visible window is incorrect, while if I slightly wiggle the camera either way you get the result on the right with the correct rectangles around the models.