texts: Does my conditional statement contain a syntax error? C++

texts:
I am not entirely new to coding, but I am new to C++. I receive the error below often, but find that it comes due to some sort of syntax error (using a minus sign instead of an equal sign, or misspelling a variable name I've already declared elsewhere), but I can't seem to find what's wrong with my most recent error:

And here's the code itself:

void ARCCharacter::Raycast()
{
  FHitResult* HitResult = new FHitResult();
  FVector StartTrace = FirstPersonCameraComponent->GetForwardVector();
  FVector EndTrace = (StartTrace* 5000.f) + StartTrace;
  FCollisionQueryParams* CQP = new FCollisionQueryParams();

  if(GetWorld()->LineTraceSingleByChannel(*HitResult, StartTrace, EndTrace, ECC_Visibility, *CQP))
  {

    DrawDebugLine(GetWorld(), StartTrace, EndTrace, FColor(255, 0, 0) true);

    if(HitResult->GetActor() != NULL)
    {
        HitResult->GetActor()->Destroy();
    }

 }

}

Also, I'm following along with a tutorial, so I'm not sure where my code diverges from the teacher's: link. I'm using XCode to work with C++ in the UE4 editor, and while I'm sure there's a simple solution to this problem, I'd like to learn about common errors beginners may encounter so I can understand the language.


texts: Game Controller that is constantly changing

texts:
I'm writing a game where the main character is a ghost, and therefor can possess just about everything. The problem is, I'm not sure how to efficiently & effectively handle the changing actions of the player.

My idea was to have the game controller have a pointer to the current Entity, and a map of keys to actions. Every entity that is possess-able will have a component called OnPossess, which will just be a wrapper around a function pointer to some global function for that type of entity. When that entity gets "possessed", the OnPossess function is called and the controllers key-to-action map is updated.

Something like this:

class Controller
{
    public:
    Entity* controlled_entity_;

    std::map<char, std::function<void(Entity*)> > action_map_;
    void OnInput(char input);
};

struct Component : public OnPossess
{
    std::function<void(Controller*)> OnPossess;
}

namespace Character_A
{
    void OnPossess(Controller* controller) {
        controller.action_map_ = Character_A_Map;
    }

    std::map<char, std::function<void(Entity*)> > Character_A_Map = { std::make_pair('l',MoveLeft),
                                                                        std::make_pair('r', MoveRight)
                                                                    };

    void MoveLeft(Entity* entity) {
        //Move left stuff
    }

    void MoveRight(Entity* entity) {
        //Move right stuff
    }
}   //End namespace Character_A

However, I feel as though this is not the way to go. Having every type of entities available actions sitting out in a global namespace with a function pointer map pointing to those functions just doesn't feel right. I had also thought about having a component that held the map of actions, with the actions just being lambdas, but then I have a bunch of copies of the same map lying around in memory.

Would there be any alternative solutions?


texts:
Okay so I want to create a main menu which includes several buttons and text fields, is there a built in library for LWJGL or would I use normal Swing and start a thread of the application?

Its a 2D game and I'm simply looking for a way of starting it from a menu rather than having it jump straight into game.


texts: Enemy Spawning method in a Top-Down Shooter

texts:
I'm working on a top-down shooter akin to DoDonPachi, Ikaruga, etc. The camera movement through the world is handled automatically with the player able to move inside of the camera's visible region.

Along the way, enemies are scripted to spawn at particular points along the path. While this sounds straightforward, I could see two ways to define these points:

Camera's position: 'trigger' spawning as the camera passes by the points
Time along path: "30 seconds in, spawn 2 enemies"

In both cases, the camera-relative positions would be defined as well as the behavior of the enemy.

The way I see it, the way you define these points will directly affect how the 'level editor', or what have you, will work.

Would there be any benefits of one approach over the other?


texts:
I'm trying to do a simple ray picking implementation to allow a user to select a cell in a grid rendered in 3D. I'm almost there, but I've ran into an issue which I can't seem to solve.

Consider the following image:

The line represents the ray. The circled part is where the mouse is, and the line's green tip is where it intersects with the grid (XZ plane). When I move the mouse around, the green tip moves almost opposite of the mouse.

What is causing this?

I am converting screen coordinates to OpenGL coordinates using gluUnproject.

After obtaining the direction and position of the mouse, I use the properties of similar triangles to obtain the XZ interception. The ratio between the direction y and position y is the same for both x and z axis. Hence multiplying the direction x, z by the ratio and using y=0 should give the location of the XZ plane intersection. Essentially:

Ray ray = ...
float ratio = ray.point.y / ray.dir.y;
Vector3 intercept = new Vector3(ray.dir.x * ratio, 0, ray.dir.z * ratio);

And yet, as the image shows, its not. Is there something wrong with my reasoning, or something I've overlooked?


texts:
I want to do game for Android that allows draw lines. These lines should be physic object at the same time.

I am good at Unity3D and I tried in Unity3D. But it is not supported.

What engine should I use? Are there anybody has an idea about which engine is used in game like this?


texts: Implicit Functions and extracting an isosurface

texts:
I recently discovered a paper on Dual Marching Cubes which produces a much reduced poly count to other methods like Dual Contouring and Marching Cubes, however a recurring theme when reading these papers is that they make reference to implicit functions.

I've been wanting to implement a form of this for procedural terrain created using a noise function (like Simplex Noise) but I don't understand how if I were to use a data structure like an Octree, or even a uniform grid, I could then use the algorithm since it wants an Implicit Function.

I think I'm going about this all wrong and not understanding something correctly, can anyone explain how it would be possible, or even if it is at all, to represent procedural terrain with an implicit function?


texts: Are there specific benefits to using XNA for 2D development if you don't plan on releasing on xbox/windows phone?

texts: I've been using XNA for a while to tinker with 2D game development, but I can't help but feel constrained by the content pipeline when targeting PC only. Things like no vector fonts or direct use of graphics files make it a pain while other frameworks do these things with no problem. I like XNA because it's robust and has a lot of support, but what are the specific benefits that I'd get developing exclusively for PC, if there are any at all?


texts:
I've got my project running and somehow it seems my vertex y components are inverted. 10 in the positive on Y goes down and 10 negative on the Y axis goes up.

I can't find anything with the initialization and I am not doing any negative scaling in the view matrix. I've never had something like this happen before, does anyone have some tips or things to look for ?

How I am sending verteces to the GPU ( Currently intermediate mode )
glVertex3f( x_pos_n, 10, z_pos );

I am using CG in the project but even without shaders the Y axis seems to be inverted.


texts: Which platform and what strategies can I use

texts:
There's this game, that I've been wanting to make for quite some time. It's a project that I've started and had to abandon in the middle a couple of times. However, this time I'm determined to finish it. I want to make a RPG (tile based) game, I'm okay with having it be 2D but am considering something in the middle of 2D and 3D. I would also like the game to be at least partially multilayer if not an MMO. I'm not a bad programmer, so I can work my way through any problems I might come across, I just don't have any experience making games, so I'm interested in any technologies I can use that I might not yet be aware of, or what type of architecture I can implement and what strategies I can use to make a decent (and secure game).

I made this game (2D tile based and partially multiplayer) before using MySql, PHP and JavaScript/Ajax. But now I would like it to be a bit more advanced with fluid graphics, and multiplayer where user's (or at least friends) can explore the maps together.

My first thought was to use Flash, PHP and MySql. Where Flash calls to a php file that returns an xml object with coordinates and etc., but I'm not sure how fast or efficient this will be.

With all that said, I'm wondering if anyone has any suggestions to what other technologies are out there that I can use. I would prefer that the game is browser based, but if it has to be run on the desktop I would like it to be at least cross-platform. I am familiar with HTML, JavaScript/jQuery, PHP, Flash, C#, WPF/XAML already and would prefer a combination of what I already know, but I don't mind learning something new either.

Any helpful links on this are appreciated as well.

Thanks in advance!


texts: Why can I not open the desktop and core folders in libGDX?

texts:
I think the problem is caused beacuse I have two JDK's. One dedicated one and another integrated from Android Studio. Before, when I start the bulid it gave me a warning:

[options] bootstrap class path not set in conjunction with -source 1.6

There is only one search I found online that did not help me.

But I can no longer reproduce this.
Can anyone help me? I dont know what I am doing wrong.
I cannot run the project, nor browse the folders in Android Studio.

Here is a screenshot:


texts: Let a time counter working when an app is closed?

texts:
Can we let a time counter working even if an app is closed? I would like to add a timer so that we have to wait XX seconds/minutes before a building is created in a game.

I don't want to use an internet connection, and if the user closes the app and just changes the time on his mobile, I cannot compare the 2 time values - before and after.

Would you know how to do this?

Thanks


texts: Increasing speed of circle over time as linear with Box2d

texts:
Assume that there is a circle and it can be moved by using keyboard arrows.Is required that increasing speed over time like increasing car speed. For example; max speed is 25 and time to reach max speed shall be 5 sec. Over 5 sec the speed will reach to max speed. Does Box2d handle that situation?.
I tried setting linear valocity but it seems to make the circle have constant speed instead of increased speed over time.

Thank You!

Note: I'm using Box2DWeb Javascript port of Box2D.


texts: How to draw a diagonal fade-in and fade-out?

texts:
How to draw a diagonal fade-in/fade-out in 2D using MonoGame draw API?

For a simple (non-directional) fade-in/out drawing the background with alpha variation do  the tricks, but what is the standard way to fade-in/fade-out directionally in 2D?

(The background is a texture, not a unicolored background)


texts: How do I manually change a sliding ball into a rolling ball in Unity 3D?

texts:
I'm a little new to this so any help will be appreciated.

Context:
I'm creating a simulated VR billiard game and trying to get the physics as realistic as possible. I have a cue ball being hit with a cue across a surface with accurate friction values calculated from real world trials.

Problem:
The cue ball slides for longer than what it would slide in the real world. Realistically, when the velocity reaches 5/7th (~71%) of its initial velocity the ball transitions from sliding to rolling. However, in Unity, the transition happens much later at around 20-10% of the initial velocity. (this is due to how Unity calculates physics of interaction as a point of contact rather than an area of contact)

Question:
I want to hard code it so that when the cue ball loses 5/7th of its initial velocity (at 71%*initial velocity), the sliding velocity is set to 0 and the cue ball continues to roll from its angular velocity. Theoretically, is this possible? or will changing the velocity/speed to zero instantly stop the ball from moving in its place? And how do I go about doing this? Thanks in advance.


texts: Orientation of SKNode in followPath Swift

texts:
I'm developing a game like price wheel where I need to touch the correct answer. For now I find replies where people says:

  Set yScale of SKNode to -1.

Or

  Set xScale of SKSpriteNode to xScale = xScale * -1.

I try but when the SKAction is executed, this take no effect. This is the code here I construct the SKNode and SKSpriteNodes:

func putNodesInScreen(){

    repeats++
    let wheel1 = SKSpriteNode(imageNamed: "find_roda_original.png")
    let wheel2 = SKSpriteNode(imageNamed: "find_roda_original.png")
    let plate = SKSpriteNode(imageNamed: "find_carro_lila.png")

    wheel1.position = CGPointMake(10, 10)
    wheel2.position = CGPointMake(300, 10)
    plate.position = CGPointMake(0, 0)

    nodes[repeats-1].addChild(wheel1)
    nodes[repeats-1].addChild(wheel2)
    nodes[repeats-1].addChild(plate)

    self.addChild(nodes[repeats-1])

    let angle : Float = -Float(M_PI)
    let rotate = SKAction.rotateByAngle(CGFloat(angle), duration: 0.5)
    let repeatAction = SKAction.repeatActionForever(rotate)
    wheel1.runAction(repeatAction, withKey: "rotate")
    wheel2.runAction(repeatAction, withKey: "rotate2")

    var sequence = SKAction.sequence([getArcPath(false), getArcPath(true)])

    nodes[repeats-1].runAction(sequence)

    }

    func getArcPath(second: Bool) -> SKAction{

        var radius: CGFloat = screenWidth*27/26 - (screenHeight/7/screenWidth/screenHeight)

        var centarArc = CGPointMake(screenWidth / 2, (((-radius) + screenHeight/2)*(1.01)))

        var end: CGFloat = CGFloat(M_PI*(270-73+25)/180.0)

        var start: CGFloat = CGFloat(M_PI*(270+73+25)/180.0)

        if(!second){
           start = start-((start-end)*(CGFloat(repeats)/13.0))
        }

         var path = UIBezierPath(arcCenter: centarArc, radius: radius, startAngle: (start-3.1416), endAngle: end-3.1416, clockwise: false)

        return (second ? SKAction.repeatActionForever(SKAction.followPath(path.CGPath,asOffset: false, orientToPath: true, speed: 250.0)) : SKAction.followPath(path.CGPath, asOffset: false, orientToPath: true, speed: 250.0))

    }

And this is the result:


texts: submeshes and dynamic batching doesnt work as expected

texts:
I'm duplicating one object with submeshes frequently, and assigning a random material from five materials to each submesh. There is batching happening, but it's not quite as efficient as I would have expected (details here).
Note objects are all less 900 vertices no light maps and ... All are dynamic batching ready

So if dynamic batching works there must be only 5 draw calls right but there isn't there is really much more than 5


texts:
I have followed a tutorial to implement a pause screen for my platformer game. I followed it thoroughly but could not get it working. When I press the escape button which I assigned under the project manager under the name "Pause", it just doesn't do anything. I checked with the Scene view as well, nothing appears. Any help would be appreciated.
Edit: The script is a component of the Main Camera, not the Canvas or the PauseUI itself.
 public GameObject PauseUI;

 private bool paused = false;

void Start()
{
    PauseUI.SetActive(false);
}

void Update()
{
   if(Input.GetButtonDown("Pause"))
   {
       paused = !paused;
   }

   if(paused)
   {
       PauseUI.SetActive(true);
       Time.timeScale = 0;
   }

   if(!paused)
   {
       PauseUI.SetActive(false);
       Time.timeScale = 1;
   }
}


texts:
This isn't a game development question per se, but here goes...

I have a 50x50 pixel space in which I need to draw five lines: X and Y axes, and one line for each of a steepest, average, and flattest slope.

I'm working with (Java) code that was handed down to me with no documentation or commentary and I've never worked with drawing on a canvas before. Here's the code for a box that measured 175x75 px. This needs to be adapted for a 50x50 area as described above.

    DrawingArea canvas = new DrawingArea(175, 75);
    canvasContainer.add(canvas);
    Rectangle rectangle = new Rectangle(0, 0, 174, 75);
    canvas.add(rectangle);
    Line slopeMainLineX = new Line(5, 70, 170, 70);
    slopeMainLineX.setStrokeOpacity(0.5);
    canvas.add(slopeMainLineX);
    Line slopeMainLineY = new Line(40, 70, 40, 0);
    slopeMainLineY.setStrokeOpacity(0.5);
    canvas.add(slopeMainLineY);
    steepestLine = new Line(40, 70, 0, 0);
    steepestLine.setStrokeWidth(3);
    canvas.add(steepestLine);
    avgSlopeLine = new Line(40, 70, 0, 0);
    avgSlopeLine.setStrokeWidth(2);
    canvas.add(avgSlopeLine);
    flattestLine = new Line(40, 70, 0, 0);
    flattestLine.setStrokeWidth(1);
    canvas.add(flattestLine);

    int steepestAngle = Math.round(site.getSlope().getMax());
    int averageAngle = Math.round(site.getSlope().getAvg());
    int flatestAngle = Math.round(site.getSlope().getMin());

    double xPointSteepestAngle = 40 + 120 * Math.cos(steepestAngle*0.0174532925);
    double yPointSteepestAngle = 70 + 120 * Math.sin(steepestAngle*0.0174532925);
    double xPointAverageAngle = 40 + 120 * Math.cos(averageAngle*0.0174532925);
    double yPointAverageAngle = 70 + 120 * Math.sin(averageAngle*0.0174532925);
    double xPointFlatestAngle = 40 + 120 * Math.cos(flatestAngle*0.0174532925);
    double yPointFlatestAngle = 70 + 120 * Math.sin(flatestAngle*0.0174532925);

    steepestLine.setX2((int) xPointSteepestAngle);
    steepestLine.setY2(70 - ((int) yPointSteepestAngle - 70));

    avgSlopeLine.setX2((int) xPointAverageAngle);
    avgSlopeLine.setY2(70 - ((int) yPointAverageAngle - 70));

    flatestLine.setX2((int) xPointFlatestAngle);
    flatestLine.setY2(70 - ((int) yPointFlatestAngle - 70));

I'm completely lost here, so any help would be greatly appreciated.


texts:
I'm using Allegro 5.0.8 al_draw_text to draw text on a bitmap (backbuffer). However, I've noticed that the first character of the string is always skipped. Moreover, whenever the same character appears in the string, it is skipped again.

For example:

font = al_load_font(path.c_str(), 100, 0);
std::string str = "01230450678";
al_draw_text(font, color, 100, 100, 0, str.c_str());

Will print "12345678", skipping all occurrences of '0'

I've tried several TTF fonts, which work with other graphic software. I've noticed that this sometimes may or may not happen with the same font, depending only on the text size on screen (font size)

Edit:
I've formatted the code and added the arguments I've used to load the font.

Edit2:
Here is a complete code to replicate this using Allegro 5.0.8.

This code should print "0123045670890", but, instead, it renders the following image:
(Note: I didn't cleared the memory because the error appears before program finishes)

//---------------------------------------------------------------------------

#include <string>

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_opengl.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/allegro_primitives.h>
//---------------------------------------------------------------------------

using namespace std;

//---------------------------------------------------------------------------

int main(int argc, char * argv[])
{
    al_init();
    al_install_keyboard();
    al_init_image_addon();
    al_init_primitives_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    al_set_new_display_flags(ALLEGRO_OPENGL);
    ALLEGRO_DISPLAY * mainWindow= al_create_display(1200, 1000);

    ALLEGRO_PATH *path = al_get_standard_path(ALLEGRO_RESOURCES_PATH);
    string file = al_path_cstr(path, '/');
    file = file + "arial.ttf";
    ALLEGRO_FONT * font = al_load_font(file.c_str(), 50, 0);

    al_set_target_bitmap(al_get_backbuffer(mainWindow));
    al_draw_filled_rectangle(0, 0, 1200, 1000, al_map_rgb(0,0,0));

    al_draw_text(font, al_map_rgb(255,0,0), 50, 50, 0, "0123045670890");

    al_save_bitmap("d:\\teste.bmp", al_get_backbuffer(mainWindow));

    al_flip_display();

    al_rest(5.0);

    return 0;
}


texts: Android app: adding background, styles, custom buttons

texts:
I am still fairly new to programming in general and android specifically.  I am working on an app that currently runs fine and does everything its supposed to do, but its only a skeleton of the app I would like to make.  Right now, my TextViews, Buttons, etc are all arbitrarily placed just so I can see them and use them to develop the app.  I am now getting to the point that I have to create the background, colors, etc and I'm not even sure what the correct terms are to search the forums and tutorials on how to do it.

I'm not looking to do anything fancy like 3D graphics, but I would like my game to look more professional than Barcode Beasties .  Maybe something closer to this .

What are the views/styles that they use and could you help me out with a bit of the correct terminology so I can figure out what I have to learn to do this?  What do I need to do to get my app that consists of standard views to the next level?


texts: Getting mousemovement despite mouselock - unity

texts:
I have lockcursor so the cursor doesn't leave the screen, but now i have to rotate an object based on mouse movement (think garrys mod item rotation) but the mouse cursor is obviusly locked to the center, is there anyway of getting the input from the mouse?

 public void GetRotated()
{
    Debug.Log(Input.GetAxis("Mouse X").ToString() + ", " + Input.GetAxis("Mouse Y").ToString());
    gameObject.transform.localRotation = new Quaternion(Input.GetAxis("Mouse X") * RotationSpeed * Time.deltaTime, Input.GetAxis("Mouse Y") * RotationSpeed * Time.deltaTime, 0, 0);
}


texts: GUI scaling: Viewport-based scaling or individual logic

texts:
I want to use scene2d for creating a GUI for a libGDX game. In scene2d all sizes are provided in pixel units (instead of percentages). So I wonder what is the best approach to deal with different screen resolutions? Two solutions came into my mind and I wonder how to proceed:

Use a fixed resolution for the GUI (e.g. 1920x1080), optimize all widgets for this size and let the viewport do the rest (so there will be super- or subsampling)
or write a resizing logic for the gui to properly adapt the widget sizes and positions to the screen's resolution

Is there any known best practice how to deal with this problem?


texts: Will there be legal issues in using cracked assets for internal development?

texts:
While the artwork for my game is being finished, can I use cracked assets for internal prototyping or testing? I am not going publish anywhere outside my company. Does it attract any legal issues?

By "cracked assets" here I mean extracting embedded graphic assets like images and .swf files from a browser cache or an encrypted URL.


texts:
I'm trying to get this object to move right across the screen until it gets close to the center and arc down smoothly into a straight downward movement. Here's what I've tried:

if (position.X < -5000)
   Velocity = Vector3.Right * speed;
else if (position.X < -1000)
{
   Velocity = new Vector3(
   MathHelper.Lerp(Velocity.X, 0, (float)gameTime.ElapsedGameTime.TotalSeconds),
   MathHelper.Lerp(Velocity.Y, -1, (float)gameTime.ElapsedGameTime.TotalSeconds), 0)
   * speed;
}
else
   Velocity = Vector3.Down * speed;

However, when it gets to where it should be arcing, it just moves to the right at blinding speed and vanishes before it hits the point where it should be going straight down. If I remove the else if, it does a sharp direction shift no problem. What am I doing wrong in that section?


texts: Custom shadow mapping in Unity 3D Free Edition

texts:
Since real time hard and soft shadows are Unity 3D Pro only features I thought I will learn Cg programming and create my own shadow mapping shader. But after some digging I found that the shadow mapping technique uses depth textures, and in Unity depth values can be accessed through a Render Texture object, which is Unity Pro only again.
So is it true, that I cannot create real time shadow shaders as a workaround to the limitations of the free version?


texts: What would be the most simple following target and neighbors avoidance algorithm in 2D space on plane?

texts:
I have ~20 or more enemies and they need to follow a target and avoid to go on top of themselves. I mean follow a target and avoid to collide with each other. Area, on which they are walking, is just a rectangle plane in 2D space.
What would be the most simple and efficient algorithm for this?
Thanks.


texts: How do I rotate a camera around the Y axis of the object it's looking at?

texts:
I'm making a camera that can currently rotate freely from the back to the front of a target object by giving it an angle and a distance.

I do the above with the following code

directionVector = new Vector3(0, Mathf.Sin (angle*Mathf.Deg2Rad), Mathf.Cos(Mathf.Deg2Rad * angle));
normalizedDirectionVector = (directionVector).normalized;

transform.position = (normalizedDirectionVector*cameraDistance) + target.transform.position;

In the above I take the direction from the angle, normalize it and then add it to the target position. And the camera sets nicely to the wanted angle. But how can I add the sideways movement(x-component) so that I could move the camera freely around the target?


texts: DX9 How to Apply HLSL Shader with StretchRect

texts:
Using DirectX 9,I'm trying to run a HLSL pixel shader on video frame data while copying it from one texture buffer to another texture buffer without displaying it. StretchRect at the end is what copies the data from pOffsceenSurface to pTextureSurface, which should pass through the pixel shader. The video data does get passed over and I can read it back, but the shader isn't being applied.

What do I need to do to process the texture through the shader? And does register(S0) get automatically filled, or how do I set the source? The code I have allows configuring register(C0), register(C1), etc. through m_pPixelConstantTable, but not the S registers. Some shaders take S0 and S1 so it needs to be configured somehow.

Here's the code

HRESULT D3D9RenderImpl::SetPixelShader(LPCSTR pPixelShaderName, LPCSTR entryPoint, LPCSTR shaderModel, LPSTR* ppError)
{
    CComPtr<ID3DXBuffer> code;
    CComPtr<ID3DXBuffer> errMsg;

    HR(D3DXCompileShaderFromFile(pPixelShaderName, NULL, NULL, entryPoint, shaderModel, 0, &code, &errMsg, &m_pPixelConstantTable));
    return m_pDevice->CreatePixelShader((DWORD*)code->GetBufferPointer(), &m_pPixelShader);
}

HRESULT D3D9RenderImpl::CreateScene(void)
{
    HR(m_pDevice->Clear(D3DADAPTER_DEFAULT, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0));
    HR(m_pDevice->BeginScene());
    HR(m_pDevice->SetFVF(D3DFVF_CUSTOMVERTEX));
    // when I debug, m_pPixelShader does get set properly)
    HR(m_pDevice->SetPixelShader(m_pPixelShader));
    HR(m_pDevice->SetTexture(0, m_pTexture));
    HR(m_pDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2));
    return m_pDevice->EndScene();
}

HRESULT D3D9RenderImpl::Present(void)
{
    HR(m_pDevice->ColorFill(m_pTextureSurface, NULL, D3DCOLOR_ARGB(0xFF, 0, 0, 0)));
    return(m_pDevice->StretchRect(m_pOffsceenSurface, NULL, m_pTextureSurface, NULL, D3DTEXF_LINEAR));
    // This line doesn't seem necessary
    // return m_pDevice->Present(NULL, NULL, NULL, NULL);
}

What's missing?

EDIT: Here's what I'm rendering to

HRESULT D3D9RenderImpl::CreateRenderTarget()
{
    // HR(m_pDevice->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, m_displayMode.Format, D3DPOOL_DEFAULT, &m_pTexture, NULL));
    HR(m_pDevice->CreateTexture(m_videoWidth, m_videoHeight, 1, D3DUSAGE_RENDERTARGET, m_format, D3DPOOL_DEFAULT, &m_pTexture, NULL));
    HR(m_pTexture->GetSurfaceLevel(0, &m_pTextureSurface));
    HR(m_pDevice->CreateVertexBuffer(sizeof(VERTEX) * 4, D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVertexBuffer, NULL));

    VERTEX vertexArray[] =
    {
        { D3DXVECTOR3(0, 0, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(0, 0) },  // top left
        { D3DXVECTOR3(m_videoWidth, 0, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(1, 0) },  // top right
        { D3DXVECTOR3(m_videoWidth, m_videoHeight, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(1, 1) },  // bottom right
        { D3DXVECTOR3(0, m_videoHeight, 0), D3DCOLOR_ARGB(255, 255, 255, 255), D3DXVECTOR2(0, 1) },  // bottom left
    };

    VERTEX *vertices;
    HR(m_pVertexBuffer->Lock(0, 0, (void**)&vertices, D3DLOCK_DISCARD));

    memcpy(vertices, vertexArray, sizeof(vertexArray));

    HR(m_pVertexBuffer->Unlock());

    return m_pDevice->SetRenderTarget(0, m_pTextureSurface);
}


texts:
So I've been messing around with directx 9 for the past few days, and I recently bump in a simple problem of vertex coloring. Can someone here with directx9 expirience solve this problem? I would appreciate that. I incuded a video to lay out this unpopular problem.

http://www.youtube.com/watch?v=rhU1vuHKAQU&feature=plcp


texts: Keypress Left is called twice in Update when key is pressed only once

texts:
I have a piece of code that is changing the position of player when left key is pressed. It is inside of Update() function. I know, Update is called multiple times, but since I have an ifstatement to check if left arrow is pressed, it should update only once. I have tested using print statement that once pressed, it gets called twice.

Problem:
Position updated twice when key is pressed only once.

Below given is the structure of my code:

void Update()
{
    if (Input.GetKeyDown (KeyCode.LeftArrow))
    {
        print ("PRESSEEEEEEEEEEEEEEEEEEDDDDDDDDDDDDDD");
    }
}

How can I fix this?


texts: IgnoreCollision on trigger callbacks not working

texts:
I am making an elevator that passes through the terrain. The character should be allowed to pass through the ground temporarily when he is within the sphere collider. The code is as follows:

using UnityEngine;
using System.Collections;

public class TerrainHole : MonoBehaviour {

    public Collider player; // assign in inspector?
    public Terrain terrain; // assign in inspector?

    void OnTriggerEnter (Collider c) {
        if (c.tag == "Player") {
            Physics.IgnoreCollision(player.GetComponent<Collider>(), terrain.GetComponent<Collider>(), true);
        }
    }

    void OnTriggerExit (Collider c) {
        if (c.tag == "Player") {
            Physics.IgnoreCollision(player.GetComponent<Collider>(), terrain.GetComponent<Collider>(), false);
        }
    }

}

By all accounts this should work, but I can't get any variation of it to work so far.

What am I doing wrong?


texts: Updating children nodes in a game engine

texts:
I am writing my own small game engine (thin layer based on SDL2) in C++. My base class is Node (contains information on an entity's position, scale, rotation, etc.), And I've got two special subclasses, Layer and Scene.

Node
|_SpriteNode
|_RectNode
|_...
|_Layer
  |_Scene

A layer can have Node children. Each time the loop runs, I call the update(int timeInterval) method on the scene being rendered, and the method loops through the vector<Node*> field containing my children. Layers propagate that call to their children, etc.

This works well until I start adding/removing children during the update. My first implementation of Layer had those two methods:

void Layer::addChild(Node* child)
{
    if(!child) return;
    _children.push_back(child);
}

void Layer::removeChild(Node* child)
{
    _children.erase(child)
}

This is, of course, stupid, since removing a Node from the vector would cause a null pointer error when the update loop ( for (auto child: _chidren) ). Using an iterator instead could fix this, but when a Node calls _parent.removeChild(this), it does not know about the iterator being used for that frame.

The solution I use at the moment is having an addition and a deletion buffer in the Layer, to which new and deleted nodes are added during the frame update. Once the frame has been rendered, the Layer performs the actual insertions and deletions from its children array. It works, and I've made a Game Jam game with this, but is seems more than sketchy to me.

I have looked through Cocos2D-X source code, and they use a simple push_back() or erase() call, which makes me think I'm missing a bigger point, or some trick that prevents the iterator issue. Is there something obvious (or not) that I missed?

Sorry if the question is dumb or missing a point. I hope I documented everything enough :)


texts: How to stop movement from moving multiple spaces when a directional key is pressed

texts:
I am making a 15 piece puzzle game and having difficulty making my sprite move one tile at a time, when i initially press the left key the sprite moves once, but after that the sprite moves multiple tiles after i press the keys again, instead of moving one tile like it should. Eventually this also messes with the sprites and some of them disappear. The code that i use to determine movement is:

if (positionx16 - positionx1 == 200 && positiony16 == positiony1)
{
    canswapleft1 = true;
}

if (oldState.IsKeyUp(Keys.Left) && newState.IsKeyDown(Keys.Left))
{
    if (positionx16 > 0 && canswapleft1 == true)
    {
        positionx16 += -widthoftile;
        positionx1 += widthoftile;
        canswapleft1 = false;
    }
}

The positionx16 is the X position of the player controlled tile, and the positionx1 referes to the X position of the 1st tile, this was repeated for each tile.


texts: How to generate a star onto a render texture with spherical warping

texts:
How would one proceduraly generate a star in a compute shader that looks like one of thes two at any size needed. Also any way transfer this into a spherical map, would be appreciated.
Goal is to create a spherical skybox of stars, (stars a pre generated, and not just decoration).
Also I have searched about everywhere for such equations, and or tutorials but have not found anything so far.
So far got accurate positioning of the stars on the spherical skybox but lack the equations to get it looking like I want.
Preferably the one on the right.

This below is what I currently have, ~~5 to 15ms processing time,    little over 30k stars

Using Unity2019.3.1f1, needs to be compute shader compatible. (if not I will convert it somehow)
Render Texture output.


texts: Wrapping each script with classes causes errors

texts:
The goal here is to change variables from another script. Thing is that they must be in classes, so for example I wrapped this code (which is from PadControl.js):

#pragma strict

public var ball : GameObject;
public var moveSpeed : float = 10;
public var rotationSpeed : float = 10;

function Update () {
    var padMove : float = Input.GetAxis("Horizontal");
    var padRotate : float = Input.GetAxis("Vertical");

    this.transform.position.x += padMove * moveSpeed * Time.deltaTime;
    this.transform.rotation.y += padRotate * rotationSpeed * Time.deltaTime;
}

function OnCollisionEnter(col : Collision){
    if(col.gameObject.name == "Ball"){
//      Debug.Log("SAY SOMETHING");
    }
}

like so:

#pragma strict

public class PadControl{
    public var ball : GameObject;
    public var moveSpeed : float = 10;
    public var rotationSpeed : float = 10;

    function Update () {
        var padMove : float = Input.GetAxis("Horizontal");
        var padRotate : float = Input.GetAxis("Vertical");

        this.transform.position.x += padMove * moveSpeed * Time.deltaTime;
        this.transform.rotation.y += padRotate * rotationSpeed * Time.deltaTime;
    }

    function OnCollisionEnter(col : Collision){
        if(col.gameObject.name == "Ball"){
    //      Debug.Log("SAY SOMETHING");
        }
    }
}

As stated in this tutorial coming from Unity's website (https://unity3d.com/learn/tutorials/modules/intermediate/scripting/statics)

But when I do it, this is the error:

  Assets/PadControl.js(12,22): BCE0019: 'transform' is not a member of 'PadControl'.
  Assets/PadControl.js(13,22): BCE0019: 'transform' is not a member of 'PadControl'.

And I really don't know what's actually going on and what should I do. Any suggestions?


texts: How to show specific item in question on trigger entry? (Unity & c#)

texts: So I have multiple, random objects on a plane, and when my player walks into them, I want them to be 'picked up'. The player can only hold one object at a time, and needs to return the item to the base before he can pick up another. Using the OnTriggerEntry function in a collider script, a set of commands are called when the player touches the object. Within the function, the 'itempickup' function from the player script is called using 'col.transform.SendMessage()'. How do I tell the itempickup function which specific object was 'picked up' in the trigger script? That is, is there a variable of some kind that acts as an ID for game objects? Thanks :)


texts:
In my game, one of the character you pick as a special ability called the dash. It allows the player to quickly move forward. Included below is the code. It just throws up a bunch of errors. This is a 3d scene

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

public class PlayerJump : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
        {
            if (Input.GetKeyDown("q"))
            {
                transform.Translate(Vector3.KeyDirection * 260 * Time.deltaTime, Space.World);
            }

        }
    }
```


texts: Is there an approach in creating an AI Framework?

texts: I am creating a board game using Actionscript 3.0. I've finished it to the point of the game playable with (computer players making random decision). I'm now working to create an AI framework/module ( Designing and creating classes that will be used to drive the AI). Is there a commonly/popular approach on creating an AI framework)? I've searhed around abit and could only find algorithms and sample codes. What I'm not looking for game/code specifics but more to thinking process in designing and modeling the AI.


texts: Modelling photo-realistic grass in realtime

texts:
I see a number of tutorials on how to create good looking grasses when creating 3D renders but can't think how to model it for realtime/use in a game's scenery.

Sure simple models with alpha cutouts can be used to create plants and trees in really awesome scenery but what about a lawn?

Are there any good tricks to achieve this effect?
I tried with a simple 4 sided box and a small texture and the number of objects needed for a decent appearance made Max crawl to a halt.

(I am thinking it may be possible with a shader but that is a whole other area so thought I would just ask about anyones experience with modelling it here)

Thanks!


texts: Sounds and buttons show up in simulator, not in an Android device

texts:
I'm a noob in android game development, started with corona sdk and outlaw.
My project runs just fine with the corona simulator on my win8, however, when building it to my android device (galaxy s3) and running it - it behaves differently than in the simulator:

First thing: in my project I have wav sound files that work just fine in the corona simulator, but on my android device the sound files do not play (I use the audio.play api).

Second thing: I have 2 buttons created with the widget.newButton api, which are displayed on a lua screen. The buttons do show in the simulator, but are not shown on the android app.

Any help will be appreciated!


texts: In Hammer, how can I make a sound come from a physics object?

texts: In hammer, I want to make a functioning radio, as in the sound comes from the radio itself and when you pick it up and move it around the sound's origin moves with the object.


texts: How to convert this resource texture creation code from DirectX 11 to DirectX 12?

texts:
I have some code below that is Directx 11 that im using to make a resource texture.

D3D11_TEXTURE2D_DESC fullScreenTextureDesc;
        ZeroMemory(&fullScreenTextureDesc, sizeof(fullScreenTextureDesc));
        fullScreenTextureDesc.Width = 800;
        fullScreenTextureDesc.Height = 600;
        fullScreenTextureDesc.MipLevels = 1;
        fullScreenTextureDesc.ArraySize = 1;
        fullScreenTextureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        fullScreenTextureDesc.SampleDesc.Count = 1;
        fullScreenTextureDesc.SampleDesc.Quality = 0;
        fullScreenTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        fullScreenTextureDesc.Usage = D3D11_USAGE_DEFAULT;

        HR(device->CreateTexture2D(&fullScreenTextureDesc, nullptr, &fullScreenTexture));

How can i convert this to directx 12?


texts: Problem with NGUI Unity 2D Sprite across devices

texts:
I have a problem with NGUI for Unity, using the Unity 2D Sprite objects.

First, have this image:

And then create an NGUI Unity 2D Sprite object in the scene. Apply this image and you get this:

Very odd. This doesn't happen if you use an Unity UI Image object or a SpriteRenderer component. But I really need to use NGUI's Unity 2D Sprite.

Then I ran the scene in several devices. Some of them display the sprite correctly - but others do not. Look:

Top-left device: iPad Mini 1: The sprite is bad.
Top-right device: iPad Mini 3: The sprite is good.
Bottom-left device: iPhone 5c: The sprite is bad.
Bottom-right device: iPhone 6 plus: The sprite is good.

I fail to understand what is the problem.

Again, this doesn't happen with sprites rendered with SpriteRenderer or Unity's builtin UI Sprite system. However, I need to do this with NGUI.

NGUI has a "NGUI Sprite" which I believe does work. But I don't want to use that one - I need to use the "NGUI Unity 2D Sprite" option.

Any ideas?

Unity 5.0.0b20


texts: How do you approach resolution independence in raster based graphics content?

texts:
Those games that are not fortunate enough to run on a locked platform spec, like handhelds, need to run across various resolution formats and aspect ratios.

In a 3D game you might have a HUD or menu GUI based on raster graphics, and in a 2D game you might have a bunch of quads which are vessels for sprites.

So my question is, how do you approach designing and operating content across various resolutions and aspect ratio? Let's assume you have a sprite character that is 300x400 pixels sprite and surrounded by a level made of tiles. On different resolutions/aspect ratios you'd see a different FOV altogether. Or if you have a HUD or a GUI menu, you'd want to keep some stuff at same positions and of same size relative to the screen. Yet, graphics source is raster bitmaps, not vector.

Obviously, problem has been addressed numerous times. I'm interested to hear abut various approaches that worked for you so far. Do you keep an arbitrary dimension agnostic 'pixel' unit that you magically transform into needed dimensions via formula based on res and aspect ratio or other approaches?

edit:

So, conclusion is to enumerate your aspect ratios. Lowest combination of aspect:resolution is the one you design important stuff into. A safe area if you will. Same aspect ratios, but higher resolutions are simple scaling issues. Art content is designed for highest resolution. Larger aspect ratios simply show more of level/FOV with information presented which is not critical as is the one in safe area. Something like in this image I made.


texts: Get the current time of animation using script Unity3d

texts: I want to know the current time of the played animation using script in Unity3d. I tried using currentState.normalizedTime but this time is not the time of the animation, like it's the time of the runtime I think. Any advice please?


texts: How to set the runtime of an animation based on attack speed?

texts:
Based on an answer I received on this question:

How to make an action perform only after an animation has run?

I am using notifications in animations to perform certain commands/actions.

See in the documentation:

https://docs.unrealengine.com/en-US/Engine/Animation/Sequences/Notifies/index.html

Before resorting to this site, I researched elsewhere for something about modifying the animation speed and the closest question I found was this:

https://answers.unrealengine.com/questions/509654/how-do-you-change-the-ratespeed-of-animation.html

Simply changing the speed of the animation, I know how to do it, but I want to control its runtime. Sort of determining how much time the animation has to play.

In the image below I show more or less the scenario I have:

Note that the notification happens at the end of the animation (where I apply the damage).

So based on the speed I set for animation to perform, every time it's finished the notification happens, applying the damage.

It turns out that the animation doesn't necessarily have the exact duration of an attack starting when the other one ends (the image below will make it easier to understand):

There is one more scenario I imagined.

In the latter case, assuming the animation is (usually) 1 second long, and the character has the maximum attack speed (I set the maximum to 2 attacks per second). So the animation would be running 2 times faster:

But the attack speed will not always be a "simple" number, I would like to know how to calculate/set it time so I have no problems when the attack speed is any number.

I want to know how to set the animation runtime and a time interval between the animation running.


texts: Distributing cross-platform .jar containing natives for LWJGL?

texts:
I'm making a game in Java using Slick2d, which depends on LWJGL. I can get everything to work in my development environment, but when I export it to a .jar, it needs the natives placed in the same directory as the .jar. What I'm asking is if it's possible to package the natives for all operating systems in the .jar, and automatically use the right ones depending on what OS was detected.

So, is this possible?


texts:
My game is a top-down multiplayer shooter where you control a space pod with 4 different weapons that do varying damage. We have all the usual stats like Kills, Deaths, and Damage Inflicted/Taken, etc. However, the one stat we have had trouble with is an Assists statistic, mainly because we can't seem to determine what should constitute an assist.

In our game, the player spawns with 224 points of health (ya random number I know), and each weapon they are hit with will take a different amount of health away (anywhere from 11-224). If the player kills another player, they recoup any lost health by 40 points.

When a player only has 40 points of health left, their pod starts to smoke to signify their low health.

Players constantly complain of being "vulched", where they will inflict 223 damage on a player, only for someone else to get the last shot and get credit for the kill.

Given this information, how would you determine when a player gets an Assist?


texts: How do I move a 2D top-down racing camera smoothly and show what's ahead of the player?

texts:
I'm trying to make a camera that follows a race car. Right now, I'm smoothing the camera movement out by moving the camera's position a fixed percentage lerp'ed from the camera's position to the car's position.

However, this makes the car appear closer to the edge of the window when it's moving toward that edge. I want the camera to appear some distance ahead of the car. This makes more sense to me--The player wants to see what's ahead.

I tried using the velocity of the car, and putting it through a logistic growth function so that it would throw out an offset for the camera position. This made close-quarters collisions too jerky. This was especially true when the car obtains a boost that applies a greater force over some time.

Then, I tried applying the logistic function only when the speed was greater than a certain amount. This didn't work. When the car obtained a boost, the camera would offset itself. This made it jerky in close-quarters collisions. When the car was moving in open space without boosts, the camera wouldn't move toward the velocity.

How do I implement a camera that follows a race car so that the window shows more of what's in front of the car without introducing jerkiness? My game is viewed from the top-down.


texts:
I am interested in making a game that I currently have a co-op experience, however I'm curious as to the best method of implementing this in HTML5.

I have made games before using straight C sockets, and also with the Net library for SDL.

What are some of my best options for doing this in a canvas-based environment?

At present, all I can come up with are either AJAX/database solutions (with a high refresh rate), or somehow implementing a PHP server that would funnel the data through sockets.

The overall gameplay would be a 2.5D platformer-ish type of game, so both clients would need to be continually updated with player positions, enemy positions, projectiles, environmental data, etc.


texts: What is the proper way to maintain the angle of a gun mounted on a car?

texts:
So I am making a simple game. I want to put a gun on top of a car. I want to be able to control the angle of the gun. Basically it can go forward all the way so that it is parallel to the ground facing the direction the car is moving or it can point behind the car and any of the angles in between these positions.

I have something like the following right now but its not really working. Is there an better way to do this that I am not seeing?

#This will place the car
glPushMatrix()
glTranslatef(self.position.x,1.5,self.position.z)
glRotated(self.rotation, 0.0, 1.0, 0.0)
glScaled(0.5, 0.5, 0.5)
glCallList(self.model.gl_list)
glPopMatrix()

#This will place the gun on top
glPushMatrix()
glTranslatef(self.position.x,2.5,self.position.z)
glRotated(self.tube_angle, self.direction.z, 0.0, self.direction.x)
print self.direction.z
glRotated(45, self.position.z, 0.0, self.position.x)
glScaled(1.0, 0.5, 1.0)
glCallList(self.tube.gl_list)
glPopMatrix()

This almost works. It moves the gun up and down. But when the car moves around, the angle of the gun changes. Not what I want.


texts: How can I get the parents and childs from the hierarchy in the same order it is in the hierarchy the structure of the hierarchy?

texts:
The line:

var gameObjects = GameObject.FindObjectsOfType<GameObject>();

Is getting all the parents and children but not in the order it is in the hierarchy. I tried to use the gos List and to add first the childs then the parents to create a List with all parents and it's childs but it's getting messed. I want to get the structure of the Hierarchy.

        var gos = new List<GameObject>();

        var gameObjects = GameObject.FindObjectsOfType<GameObject>();
        for (int i = 0; i < gameObjects.Length; i++)
        {
            if (gameObjects[i].transform.childCount > 0)
            {

                //get children
                GameObject[] children = new GameObject[gameObjects[i].transform.childCount];
                for (int z = 0; z < children.Length; ++z)
                {
                    children[z] = gameObjects[i].transform.GetChild(i).gameObject;
                    gos.Add(children[z].gameObject);
                }
            }
            else
            {
                gos.Add(gameObjects[i]);
            }
        }


texts:
in a previous question asked here:how-to-create-a-hexagon-world-map @Tim Holt has provided code that does the job that i'm wanted to do, the only difference I would like is to have it as squares rather than hex. Is this easy to convert, or is there a better way?
thank you.


texts: Unity procedural TileMap generation without creating gameobject per tile

texts:
I've been searching internet to find an efficient way to create a procedural tilemap without creating a GameObject per tile.
All the TileMap tutorials I've found are creating tiles by creating hundreds of GameObjects. Thus the hierarchy in Unity is expanding unexpectedly.

I'm pretty sure this is not the "right" way to do it. Especially after seeing the new Unity 2D tools that supports tilemaps. Unity made it so, you can create tiles in "one" gameobject, not for each tile.

So, how do I do it in the right and effiecent way?


texts: GLSL: gl_ModelViewMatrixTranspose vs. gl_ModelViewMatrix

texts:
What is the difference between doing these two operations?
Don't the first transform the vector from model space to view space? Then what does the second operation do?

gl_ModelViewMatrix * vec4(vector, 0.0)

gl_ModelViewMatrixTranspose * vec4(vector, 0.0)


texts: Pixel Shader, YUV-RGB Conversion failing

texts:
I am tasked with playing back a video hthat comes in in a YUV format as an overlay in a larger game. I am not a specialist in Direct3d, so I am struggling. I managed to get a shader working and am rendering 3 textures (Y, V, U). Sadly I am totally unable to get anything like a decent image. Documentation is also failing me. I am currently loading the different data planes (Y,V,U) in three different textures:

m_Textures = new Texture[3];
// Y Plane
m_Textures[0] = new Texture(m_Device, w, h, 1, Usage.None, Format.L8, Pool.Managed);
// V Plane
m_Textures[1] = new Texture(m_Device, w2, h2, 1, Usage.None, Format.L8, Pool.Managed);
// U Plane
m_Textures[2] = new Texture(m_Device, w2, h2, 1, Usage.None, Format.L8, Pool.Managed);

When I am rendering them as R, G and B respectively with the following code:

float4 Pixel(float2 texCoord: TEXCOORD0) : COLOR0
{
    float y = tex2D (ytexture, texCoord);
    float v = tex2D (vtexture, texCoord);
    float u = tex2D (utexture, texCoord);

    //R = Y + 1.140 (V -128)
    //G = Y - 0.395 (U-128) - 0.581 (V-128)
    //B = Y + 2.028 (U-128)

    float r = y; //y + 1.140 * v;
    float g = v; //y - 0.395 * u - 0.581 * v;
    float b = u; //y + 2.028 * u;

    float4 result;
    result.a = 255;
    result.r = r; //clamp (r, 0, 255);
    result.g = g; //clamp (g, 0, 255);
    result.b = b; //clamp (b, 0, 255);

    return result;
}

Then the resulting image is - quite funny. I can see the image, but colors are totally distorted, as it should be.

The formula I should apply shows up in the comment of the pixel shader, but when I do it, the resulting image is pretty brutally magenta only. This gets me to the question - when I read out an L8 texture into a float, with

float y = tex2D (ytexture, texCoord);

what is the range of values? The "origin" values are 1 byte, 0 to 255, and the forum I have assumes this. Naturally I am totally off when the values returned are somehow normalized. My Clamp operation at the end also will fail if for example colors in a pixel shader are normalized 0 to 1. Anyone an idea how that works? Please point me also to documentation - I have not found anything in this regard.


texts:
I'm trying to figure out a way to show the path a ball will travel, so that the player can line up a shot before they fire the ball.

I can't think of a way to calculate this path in advance and show it to the player, especially if it involves collision detection. At first I thought I would run the game at a super high speed for one update, plot the path with some dotted lines where the ball bounced, and then in the next frame hide the 'tracer' ball. This seems to have two issues - Calculating collision detection without actually updating the frames and collision detection getting less reliable at high speeds.

If they were straight lines I think I could figure this out in a while loop, but trying to take into account the speed of the ball, the curve of the path, the reflecting from other objects..it all seems a bit much.

I'm not looking for any code and this isn't a platform specific question, more just help trying to figure out conceptually how this would work. Can this be done? Are there techniques to achieve this?


texts: What's a good way to distribute delayable tasks between frames to avoid lost frames?

texts:
I'm having a problem with finding a good way to keep the framerate high and at the same time keep running methods of game world update. I figured I could just put those methods in a thread so they are executed simultaneously with the rest of the game loop methods, but the threads tend to hog resources, which causes lost frames.

Then I thought I should break down tasks in parts and only run a little piece of a bigger task each frame or so. But this turned out to be way much slower than expected, and it also took a lot of time to implement.

After thinking some more about threads I found another way to use them: Thread.Suspend and Thread.Resume methods ought to prevent threads from keeping hogging all the resources until the game drawn or calculates some physics. But I also read that it's risky because you can't know what the thread is doing right before you suspend it, which may cause big problems. My tasks are mostly independent from each other, but still, some of them rely on objects which are sometimes edited by two separate threads, and sticking those operations together is an undesired solution.

Are these options any good? What other solutions for this problem do you know?


texts: How to avoid an applied force from effecting one particular Rigidbody2D

texts:
I am creating a 2D side-scroller car race game with zombies. In this game, I set up a feature through which the player can shoot the zombies from the car, as well.

The problem is that when I apply force to shoot the bullet towards the right, the car also gets effected by that force, i.e it just moves a lot in reaction to the bullet shot. I don't want this behavior. I want the car to remain calm and just shoot.

Is there any way to exclude one particular rigidbody, i.e the rigidbody attached to the car, from applying the force the bullet rigidbody is using?


texts: How to flip a quad (openGL es 2.0 Android / Java)

texts:
How would one go about 'flipping' a quad, either horizontally or vertically? (Just a single quad, not everything in view).

I know how to rotate a quad, this is my rotation method:

public void rotate(float x, float y, int angle){

    //Convert co-ordinates (Following section just converts my coordinates

    //Left hand
    xPlotLeft = (-MyGLRenderer.ratio)+((x)*MyGLRenderer.coordStepAmountWidth);
    //Top
    yPlotTop = +1-((y)*MyGLRenderer.coordStepAmountHeight);
    //Right hand
    xPlotRight = xPlotLeft+((quadWidth)*MyGLRenderer.coordStepAmountWidth);
    //Bottom
    yPlotBottom = yPlotTop-((quadHeight)*MyGLRenderer.coordStepAmountHeight);

    //Center of quad (Along the x)
    centreX = xPlotLeft + ((xPlotRight-xPlotLeft)/2);
    //Center of quad (Along the y)
    centreY = yPlotBottom + ((yPlotTop-yPlotBottom)/2);

    //Rotate the quad

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

}

I'm unsure how to do something similar just to flip (or 'mirror') the quad.


texts: Proper use of async, await and task.delay for a game loop

texts:
I'm currently in the process of making a game loop in a console application. I'm trying to make the game loop wait at the end of its loop for (1000*10000/fps) - ElapsedTicks to put a cap on game loop speed. For reference 1 millisecond is 10,000 ticks.

If the ElapsedTicks < FrameTimeTicks I execute await Task.Delay(FrameTimeTicks - ElapsedTicks) but this ends my console application.

The code responsible is the await Task.Delay so I assume I'm not using it properly.

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApp1
{
    class Program
    {
        static byte fps = 30;
        public static byte Fps { get { return fps; } set { fps = value; } }
        //user specified fps

        static long frameTimeTicks = (1000 * 10000) / Fps;
        static long FrameTimeTicks { get { return frameTimeTicks; } }
        //amount of ticks desired in one frame

        static bool draw = true;
        public static bool Draw { get { return draw; } set { draw = value; } }

        static long elapsedTicks;
        static long ElapsedTicks { get { return elapsedTicks; } set { elapsedTicks = value; } }
        //ticks elapsed in one game loop

        static void Main(string[] args)
        {
            GameLoop();
        }

        static void UpdateGame()
        {
            int a = 0;
            a++;
        }
        static void Render()
        {
            Console.WriteLine("@");
        }

        public static async void GameLoop()
        {
            Stopwatch gameLoopTicks = Stopwatch.StartNew();

            while (true)
            {
                gameLoopTicks.Restart();

                if (Console.KeyAvailable == true)
                {
                     char KeyPressed = Console.ReadKey().KeyChar;
                }
                UpdateGame();
                if (Draw == true)
                {
                    Render();
                }
                ElapsedTicks = gameLoopTicks.ElapsedTicks;
                if (ElapsedTicks > FrameTimeTicks)
                {
                    Draw = false;
                }
                else
                {
                    Draw = true;
                    await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
                }
            }
        }
    }
}

I Have also tried this variation but to the same result, my console application ends.

public static async void GameLoop()
    {
        Stopwatch gameLoopTicks = Stopwatch.StartNew();
        async Task PauseGameLoop()
        {
            //Console.ReadKey(); execution ends here!
            await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
            GameLoop();
        }

        while (true)
        {
            gameLoopTicks.Restart();

            if (Console.KeyAvailable == true)
            {
                 char KeyPressed = Console.ReadKey().KeyChar;
            }
            UpdateGame();
            if (Draw == true)
            {
                Render();
            }
            ElapsedTicks = gameLoopTicks.ElapsedTicks;
            if (ElapsedTicks > FrameTimeTicks)
            {
                Draw = false;
            }
            else
            {
                Draw = true;
                await PauseGameLoop();
            }
        }

Task.Delay MSDN, await MSDN. Am I tackling this problem the wrong way ? This post is why I chose this method. Thanks for the help!


texts: Collision2d Unity To Change Another Scripts Int Value

texts:
I am looking to decrease the value stored in my script "progress" which takes 1 away from a value curHealth, when the Player sprite to which this script "collision", is attacked/ touching the Enemy 2d box collider.
The decreasing of the value doesn't happen when the two objects touch. Both the Player and the Enemy have 2dbox colliders and other shape 2d colliders.

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

public class collision : MonoBehaviour {

    public progress Progress = GameObject.FindGameObjectWithTag("HealthBar").GetComponent<progress>();

    void OnCollisionStay2d(Collision2D coll){
        if (coll.gameObject.name == "Enemy") {

            Progress.curHealth -= 1;

            }
        }

}


texts: As of now, to get random movement of my enemies, I am adding a Rigidbody and a BoxCollider then "throwing" them (i.e. adding velocity) in a random direction for a random amount of time and making them choose a new direction if ever they get outside of their designated area. This does not seem to work that well all the time. Sometimes they manage to get themselves stuck inside obstacles which should be impossible. The more I add guys, the more it seems the physics can't keep up or something with the collisions. Is there a better method to random movement or is "throwing" them perfectly valid? Is my method expensive and terrible? I might have around 50 guys active at a time and perhaps a few hundred to a thousand static obstacles each with their own colliders.


texts: Using compressed(ETC1) textures in LibGDX

texts:
I use standard android tool for compressing PNG texture and archiving it with gzip:

/android-sdks/tools/etc1tool texture.png --encodeNoHeader
gzip texture.pkm

Then I try to load it:

FileHandle file = ...;
ETC1.ETC1Data data = new ETC1.ETC1Data(file);
ETC1TextureData td = new ETC1TextureData(data, false);
Texture texture = new Texture(td);

But I get an java.nio.BufferOverflowException inside ETC1Data (FileHandle pkmFile) constructor:

  in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read())));
  int fileSize = in.readInt();
  compressedData = BufferUtils.newUnsafeByteBuffer(fileSize);
  int readBytes = 0;
  while ((readBytes = in.read(buffer)) != -1) {
      compressedData.put(buffer, 0, readBytes);//Exception occurs here
  }
  compressedData.position(0);
  compressedData.limit(compressedData.capacity());

How to fix it? Thanks.

ps if it's important: unarchived pkm file size is 33KB


texts: Should items in an RPG be hardcoded or loaded in some other way?

texts:
Should static weapons (ie.. Iron Sword, Mythril Axe) be their own (static) classes that derive from something like ItemWeapon, which itself is derived from a standard Item class with their own (inherited) methods?

Or possibly should there be just a standard Item class, an ItemWeapon class, and then every weapon is just an ItemWeapon instance loaded in at the start of the game?

If I was going to do that approach, where would I be loading all the items and weapons into the game? init?

If some weapons have special properties such as doing multiple attacks or a different effect, would it be beneficial to make them the separate classes to do it on an as-is basis instead of having every Weapon in the game have that function except it doesn't do anything?


texts: How to make shadows softer as distance increases?

texts:
I'm trying to make shadows become more blurry as the distance between the caster and receiver, so they look a little more realistic.

What method can I use to achieve this?


texts:
I want two vertices of editable spline become one. Neither fuse, nor weld helps: vertices remain separate.

Here is a video: http://youtu.be/bp3OJPeKapc


texts: Persistent Browser Based Game: To Captcha or not to Captcha?

texts:
I've been working (off-and-on) on a pbbg that's pretty old school.  If you've ever played Carnage Blender then you get the idea.

If not, it's a simple idea that's been done a lot:  A player is allocated a certain number of "points" each day, and spends those points to attack other players.  Points accrue over time, up to a certain cap.

The point system is designed to prevent over-achievers from completely out-pacing casual players.

In the case of carnage blender, a CAPTACHA system prevents a user from "gaming" the system with a bot or a script designed to use all of their points each day with minimal effort.  Every once in a while a random CAPTCHA is displayed, and if not passed the user will be suspended for an hour.

What I'm wondering is how to make this more user friendly for my game.  I recognize that I must prevent bad behavior like this, and I could easily take the same CAPTCHA approach, but is there a more user friendly alternative?

Initial research uncovered ASIRRA by Microsoft, but the fluffy/cute vibe doesn't work well with my intended game theme.

UPDATE
What I'm most interested in are alternatives to the standard "spell this word" CAPTCHA.  I want to try to keep game-play as uninterrupted as possible for the good players.

I've seen what I call One-Time-Use CAPTCHAs, like asking a user "what is five plus six minus two?"  But this would require too much effort compiling a large enough database of questions to foil the malicious users.  Especially since the CAPTCHA is intended to be used so often.

UPDATE #2
As Joe Wreschnig pointed out in his answer, having a CAPTCHA system to limit bots from playing the game faster than humans is a bit redundant if turns are limited per day.  I didn't explain my point system to-the-letter, and that was my fault.  In reality, 10 or 20 points accrue every few minutes, and cap off at 200.  So, a very competitive player could return every few hours and use his points.  I want to reward those people who like my game so much that they return so often.  If I prevent them from playing until the next day when they get their points, I would be turning away players who would otherwise be enjoying my webgame.  This prevents a player from spending points constantly while still giving them a few points every few minutes.

This is open to abuse.


texts: I get weird perspective using GLM where the depth is flipped. Please help

texts:
The depth is rendered wrong and I can't figure out why.

using namespace std;
using namespace glm;
int width = 640;
int height = 480;
float aspect = (float)width/height;
int fps = 60;

void start(){
  glClearColor(0.0f,0.2f,0.6f,1);
  glEnable( GL_TEXTURE_2D );
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);
  glFrontFace(GL_CW);
  glCullFace(GL_BACK);
  glEnable(GL_CULL_FACE);

  mat4 projectionMatrix = perspective(radians(60.0f),aspect, 0.1f, 1000.0f);
  mat4 modelViewMatrix = translate(vec3(0,-25,-100));
  modelViewMatrix *= rotate(radians(50.0f),vec3(0.f, 1.f, 0.f));
  modelViewMatrix *= rotate(radians(-90.0f),vec3(1.f, 0.f, 0.f));
  mat4 modelViewProjMatrix = projectionMatrix*modelViewMatrix;

  Shader shader;
  shader.load("vertex.glsl","fragment.glsl");
  shader.bind();
  shader.uniform("modelViewProjMatrix",value_ptr(modelViewProjMatrix));

  Model model;
  model.load("res/bob.md5mesh");

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  model.render();
  glutSwapBuffers();
}

void mainloop(int val){
  glutTimerFunc(1000/fps,mainloop,val);
}
int main(int argc, char* args[]){
  glutInit(&argc,args);
  glutInitContextVersion(3,0);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
  glutInitWindowSize(width,height);
  glutCreateWindow("Test");
  glewInit();

  start();
  glutTimerFunc(1000/fps,mainloop,0);
  glutMainLoop();
  return 0;
}

However, I found a way to fix it by multiplying the perspective by scale(1,1,-1),
but it seems kind of a hack to me.

mat4 projectionMatrix = perspective(radians(60.0f),aspect, 0.1f, 1000.0f) * scale(vec3(1,1,-1));
mat4 modelViewMatrix = translate(vec3(0,-25,100));

I'd really appreciate it if someone can tell what I'm doing wrong.


texts:
I'm creating a 2D game similar to Mario. What is a best practice to allow the character to move through the level given a limited screen size?

The way I have it now is the Player moves across the screen, and when they reach the far right edge, you reset them to the far left of the screen (basically teleport them back to the left side...). And if they're at the far left edge, keep resetting them to the far left side (to simulate a wall)

Check Player Bounds:

public void checkPlayerBounds (Player player) {
    if (player.getY() >= height-(playerHeight+25)) {
        player.reset("down");
    }
    else if (player.getY() < 0) {
        player.reset("up");
    }
    else if (player.getX() > width-(playerWidth)) {
        player.reset("right");
    }
    else if (player.getX() < 0) {
        player.reset("left");
    }

Reset:

public void reset(String val) {
    if (val.equals("down"))
        yLoc = gameboard.getHeight()-(height+30);
    if (val.equals("up") )
        yLoc = 0;
    if (val.equals("left"))
        xLoc = 0;
    if (val.equals("right"))
        xLoc = 0;
}

So I'm basically just either teleporting them when they get to the far right to simulate them (moving forward), at which point I would draw the applicable background and items (each time person reaches far right side, have a counter that is associated with the correct things to load on the screen)...

Or, should it be that the actual Player character doesn't move when you press right... it's actually the background items and map that moves (loads)?

If so, how would that look from a pseudocode/design perspective?

Thank you


texts: There are few events in my game, like complete levels , complete puzzles , kill enemies and so on. Each such event will reward the player points and bonus powers. Now each "master" task (for example puzzles) can reward the player different points so the hierarchy can be big. How do I design such module ?


texts: Point[] and Tri not "could not be found"

texts:
Hi I'm trying to learn how to load a .obj file using OpenTK in windows Forms.  I have seen a lot of examples out there, but I do see almost everyone uses List<Tri>, and Point[].  Code examples show these highlighted like there IDE know what these are; for example

List<Tri> tris = new List<Tri>();

but mine just returns "The type or namespace name 'Tri' could not be found"
is there an include I need to add or a using I am missing.  Currently have this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

EDIT: I have been trying to piece it together primarily from using code samples found here:

http://www.opentk.com/node/1946

As well as from here
Missing triangles in model

I have been trying to piece it together primarily from using code samples found here

http://www.opentk.com/node/1946

As well as from here
Missing triangles in model


texts: 2D character controller in unity (trying to get old-school platformers back)

texts:
This days I'm trying to create a 2D character controller with unity (using phisics). I'm fairly new to physic engines and it is really hard to get the control feel I'm looking for. I would be really happy if anyone could suggest solution for a problem I'm finding:

This is my FixedUpdate right now:

public void FixedUpdate()
{
    Vector3 v=new Vector3(0,-10000*Time.fixedDeltaTime,0);
    _body.AddForce(v);

    v.y=0;
    if(state(MovementState.Left))
    {
        v.x=-_walkSpeed*Time.fixedDeltaTime+v.x;
        if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=-_maxWalkSpeed;
    }
    else if(state(MovementState.Right))
    {
        v.x= _walkSpeed*Time.fixedDeltaTime+v.x;
        if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=_maxWalkSpeed;
    }

    _body.velocity=v;

    Debug.Log("Velocity: "+_body.velocity);
}

I'm trying here to just move the rigid body applying a gravity and a linear force for left and right. I have setup a physic material that makes no bouncing and 0 friction when moving and 1 friction with stand still. The main problem is that I have colliders with slopes and the velocity changes from going up (slower) , going down the slope (faster) and walk on a straight collider (normal). How could this be fixed? As you see I'm applying allways same velocity for x axis.

For the player I have it setup with a sphere at feet position that is the rigidbody I'm applying forces to.

Any other tip that could make my life easier with this are welcomed :).

P.D. While coming home I have noticed I could solve this applying a constant force parallel to the surface the player is walking, but don't know if it is best method.


texts: What platform were old TV video games developed on?

texts:
I am very eager to know how TV video games (which we all used to play in our childhood) were developed and on which platform.

I know how games are developed for mobile devices, Windows PC's and Mac but I'm not getting how (in those days) Contra, Duck Hunt and all those games were developed. As they have high graphics and a large number of stages. So how did they manage to develop games in such a small size environment and with lower configuration platform?


texts:
In my game i have a delta timer based almost exactly on the page from here

http://wiki.lwjgl.org/index.php?title=LWJGL_Basics_4_%28Timing%29

But if the the main loop is fast enough,  my delta time variable is 0. This causes problems because it often happens several times in a row.
I don't want to force a frame cap either. How can I remedy this?

EDIT: Setting a frame cap works,  it only happens when the frame isn't capped. I've set delta to a minimum of 1, but that doesn't make it smooth.  I could add a delay of one if it's zero, but that only fixes it for the next frame.


texts:
I wrote a MatrixStack class in C# to use in a SceneGraph. So, to get the world matrix for an object I am suposed to use:

WorldMatrix = ParentWorld * LocalTransform

But, in fact, it only works as expected when I do the other way:

WorldMatrix = LocalTransform * ParentWorld

Mi code is:

public class MatrixStack
{
    Stack<Matrix> stack = new Stack<Matrix>();
    Matrix result = Matrix.Identity;

    public void PushMatrix(Matrix matrix)
    {
        stack.Push(matrix);
        result = matrix * result;
    }

    public Matrix PopMatrix()
    {
        result = Matrix.Invert(stack.Peek()) * result;
        return stack.Pop();
    }

    public Matrix Result
    {
        get { return result; }
    }

    public void Clear()
    {
        stack.Clear();
        result = Matrix.Identity;
    }
}

Why it works this way and not the other? Thanks!


texts:
I'm transforming objects in 3D space by transforming each vector with the object's 4x4 transform matrix. In order to achieve hierarchical transform, I transform the child by its own matrix, and then the child by the parent matrix. This becomes costly because objects deeper in the display tree have to be transformed by all the parent objects.

Is there a faster way to transform vertices to achieve hierarchical transform?


texts: Can I make a multiplayer Android Game using Android Studio?

texts:
I want to create a multiplayer android game, where the clients connect together via a web server.

My question is: Is it possible to make this kind of games using Android Studio with other libraries like LibGDX and Java sockets?


texts: Representing multi-tile objects in a tilemap

texts:
I'm building an isometric tiled game, where the terrain and objects are represented by a 2-dimensional array of lists. Depth of objects on the map is derived from the tile (and a per-tile sorting routine), the objects are updated/drawn by going over the entire map, and it is important to know whether a tile is occupied or not for interaction/collision purposes.

Now, I want to have objects that are larger than a single tile (say, a 2x2 or 2x3 object). Drawing them this way is trivial, however, there is the occupation detection requirement. Putting the same object or dummy objects into the array merely to indicate that the tiles are taken doesn't seem like an elegant solution, but neither does checking surrounding tiles for possible big objects, each time the occupation status of a tile is requested.

Is there a more elegant solution that I've overlooked?


texts: How do engines like Unreal relate to OpenGL or DirectX?

texts:
I'm completely new to computer graphics, and even more so, to game development. I am searching for information to learn the basics, quickly. I have one question in my head; how do engines like the Crytek Engine or the Unreal Engine relate to OpenGL or DirectX?

I'm very interested in game physics, but I can't figure out how the physics, graphics, and engine come together; there are gaps I can not fill.


texts: Bullet Physics Integration - direct movement of rigid bodies

texts:
I'm adding bullet physics to my engine. The physics simulation bits are all working nicely, but one bit I'm struggling with is being able to move objects using their co-ordinates, and then have them affect other bullet objects. I currently have this code just before I step the simulation, and this moves all of the objects to the co-ordinates that the game engine thinks the object should be, due to outside movement.

btTransform trans;
trans.setFromOpenGLMatrix(glm::value_ptr(host->getTransMat() * host->getRotMat()));

motionState->setWorldTransform(trans);
body->setWorldTransform(trans);

Then I step the simulation, and move every object to where bullet thinks it should be. I am aware there are nicer ways to do this part (custom written motionstate classes I think) but I want to get the logic down first. This works, but moving a cube directly into another causes the second cube to just shake a bit.

I've read in  few places I should be applying forces to objects, but:

I don't really want to expose the btRigidBody and physics stuff to the core gameobject, and
I have a lot of code that does it's own movements using co-ordinates, and I don't really want to rewrite it, although I will if it's the only way.

Could I replace the code below with something that compares the position of the gameobject to the rigidbody's position, and applies the correct force to make that happen? How would I implement this code? It can't be as simple as F = MA can it, given that this would happen any frame?

Edit 1:

I have implemented the formula provided by DMGregory and I've not had any success. I've tried swapping this out for applyCentralImpulse too. The objects just stay stationary and anything falling just goes into hyper speed. This runs for every  physics object just before step sim, and then the simulations positions are applied to back to their hosts.

    if (host == nullptr)return;

btVector3 newPos = convert(host->getPos());

btVector3 oldPos = body->getWorldTransform().getOrigin();

btVector3 dist = newPos -oldPos;

btVector3 acc = 2 * ((newPos - oldPos -( body->getLinearVelocity() * timeStep)) / (pow(timeStep, 2)));

if (dist.length() > btScalar(0.1f))
{
    std::cout << acc.length() << "large acc \n";
}

body->applyCentralForce(mass * acc);


texts: How should I go about handling nonuniformed sprite sheet with JSON data?

texts:
This might be a lenghty question so bare with me.

I'm developing a 2D game i Monogame framework and I'm stuck with it comes to handle large sprite sheets with different frame width, height and animation. I want to load a sprite sheet that has different animation.

Like this one

Taken from this question

Some frames in this sprite sheet have different width and height, meaning that I can't use a uniform split with spritesheets width / amount of columns because it will not work with all the frames. I have used a tool that gives me cordinates in JSON format like this

{
   "@imagePath": "sprites.png",
   "SubTexture": [
      {
         "@name": "spriteframe1.png",
         "@x": "862",
         "@y": "0",
         "@width": "112",
         "@height": "120"
      },
      {
         "@name": "spriteframe10.png",
         "@x": "0",
         "@y": "320",
         "@width": "252",
         "@height": "156"
      }
}

But here I have problem understanding how I should handle these different frames. How can I switch between animation frames and make sure that the animation loops with state of the object?

E.G If the object in this case flies, I want to loop trough the wing animation but how should I handle it so that only the "Fly-frames" are being looped?

At the moment I have all the frames in a list where every element is a frame with its own x,y,width and height metadata.


texts:
I'm developing a flight simulator based on Riemer's Blog tutorial (XNA C#). To control the aircraft, I use the following code:

Quaternion additionalRotation = Quaternion.Identity;
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Forward, roll);
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
model_ROTATION *= additionalRotation;

This only executes pitch and roll. I wanted to add code so that if the aircraft is rolling, then it should rotate to right or left (yaw) so I changed the code to the following:

Quaternion additionalRotation = Quaternion.Identity;
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Forward,roll);
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Up, yaw);
additionalRotation *= Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
model_ROTATION *= additionalRotation;

This behaviour is not so realistic; when I roll the aircraft rotates to right/left (yaws), but at the same time it loses altitude and I must pitch up (pull handle) to avoid crashing.

Is there any solution to make slew rotation (yaw) without losing altitude.


texts: How can I split up a large model into an octree codewise?

texts:
For collision detection, I am attempting to split up a large model into an octree.

If we take this black thing thing to be the ship (104,000 vertices):

Then I would like to split up the faces

I could easily split them up, but the problem is one of location. For example, if we take the bottom left chunk, how can I know that the projectile (in this case, a cannonball) is at that specific chunk?

And also how can I define the areas of the chunks in the first place? And for that matter, I need them to rotate with the ship as well!

I'm hopelessly lost as of how to do this, and so I'm hoping someone can help me out.


texts: Enemy gun won't aim properly when collision line is flipped | Game maker studio

texts:
When the enemy move's to the right their gun faces right. When they move left the gun will face left as it should. When the player collides with the enemy collision line on the right side, the enemy gun will point towards the player properly.

When the player is on the left side of the enemy and hits the collision line, the enemy gun will sort of point towards the player but not facing the right direction.

 Step Event of Enemy gun object:

//image_xscale = 1 is looking to the right, -1 is left
// I use image_angle so the enemy gun will aim at the player on x and y axis

if obj_testEnemy.image_xscale == 1 { //When the enemy is looking to the right
    if (collision_line(x, y, x + 128, obj_testPlayer.y , obj_testPlayer, false, true)) {
        image_angle = point_direction(x,y,obj_testPlayer.x,obj_testPlayer.y); //how it aims at the player
    } else {
        image_angle = obj_testEnemy.image_xscale; // faces the correct direction when not colliding
    }

} else {
    if (collision_line(x, y, x - 128, obj_testPlayer.y , obj_testPlayer, false, true)) {
        image_angle = point_direction(x,y,obj_testPlayer.x,obj_testPlayer.y);
        image_xscale = -1; //gun should be facing left but it's not
    }
}

I don't understand why the gun won't face left when the collision line is facing left

Working:

Not Working:


texts: How do I find the angle between two vectors?

texts:
I have 3 points on my screen:

a = a point which is (c.x, 0) makes a line pointing straight up
b = a user input touch, can be anywhere on the screen
c = a moving object

       a
_______.________
|      |       |
|      |       |
|   b  |       |
|  .   |       |
|   \  |       |
|    \ |       |
|     \|       |
|      | c     |
|______._______|

I have drawn some lines so that you can see the vectors.

I want to be able to get the angle between a and b. I have tried this, but it doesn't work, does anyone know what I'm doing wrong?:

//v1 moving object
float boxX = this.mScene.getLastChild().getX();
float boxY = this.mScene.getLastChild().getY();

//v2 user touch
float touchX = pSceneTouchEvent.getX();
float touchY = pSceneTouchEvent.getY();

//v3 top of screen
float topX = boxX;
final float topY = 0;

float dotProd = (touchX * topX) + (touchY * topY);

float sqrtBox = (touchX * touchX) + (touchY * touchY);
float sqrtTouch = (topX * topX) + (topY * topY);

double totalSqrt = sqrtBox * sqrtTouch;
double theta = Math.acos(dotProd / Math.sqrt(totalSqrt));

The answer I usually get is between 0 and 1.
How do I fix this so that I get the angle in degrees?


texts: Getting vector relative to other vector in rotating object

texts:
So I have a rotating object a. It is rotating at non-constant speed around it's local x axis. It is parented to object b. When the object a rotates, it's local x axis stays facing the same direction relatively to object b, but not the local y and local z axis.

In image the problem is explained a bit better. So I need to get a vector that is relative to the local x axis, but rotated by 90 degrees. And it should always match the b object's local y arrow's rotation around it's local x arrow. And I need to obtain a vector in global axis. I hope that you understand my problem.

So all I need is the math behind. Of course, if there is need for a dot product or cross product or something similar down there, please, don't start typing down all the math of that function:D


texts:
Strategy games (such as Door Kickers) use a player's unit's line-of-sight as a major game feature. To provide feedback to the player regarding which areas are in view and which are not, different colours are used to display areas that are currently visible by a unit and areas which are not.
Can anyone recommend an approach for creating this effect in a shader?


texts: How to make a new powerup reset the WaitForSeconds from previous powerup?

texts:
I'm making a game where the player is pushing objects outside a plane. Every round there's an additional ball (GameManager.cs):

 for (int i = 0; i < enemiesToSpawn; i++)

But every round the player gets a powerup as well:

 if (enemyCount == 0)
    {
       roundNumber++;
       SpawnEnemyIntruders(roundNumber);
       Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation);
    }

In the PlayerController.cs the code looks like this:

   private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Powerup"))
    {
        hasPowerup = true;
        Destroy(other.gameObject);
        StartCoroutine(PowerupCountdown());
        powerupParticle.Play();
        playerAudio.PlayOneShot(powerupSound, 1.0f);
    }
}

IEnumerator PowerupCountdown()
{
    yield return new WaitForSeconds(5);
    hasPowerup = false;
    powerupParticle.Stop();
}

How can I reset the WaitForSeconds, or do something similar, every time the player gets a powerup?


texts: How do I find the name of the current audio clip being played?

texts:
I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so.

How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played?

This is my "LevelMaster" script which is responsible for handling the audio in each scene.

public class LevelMaster : MonoBehaviour
{
private AudioManager AudioManager;

[SerializeField]
private string trackName;

private void Start()
{
    AudioManager = GameObject.Find("AudioManager").GetComponent<AudioManager>();
    AudioManager.Play(trackName);
}

public void PlaySound(string soundName)
{
    AudioManager.Play(soundName);
}

public void StopSound(string soundName)
{
    AudioManager.Stop(soundName);
}


texts: How do I create a spherical world to explore?

texts:
So to preface this question, I have done a lot of research on this, but most of it has proven unhelpful, possibly because I'm not sure the proper way to phrase what it is that I'm trying to ask, so I might make this a little long-winded to get my point across.

The basic idea that I am trying to explore is a small planet that can be navigated by the player, but I also want this planet to be similar, but different for each playthrough (hence the procedural-generation tag). At first, I looked into doing this by simply creating a sphere which has it's own type of gravity (doesn't have to be too realistic), but research proved that this had many (too many) obstacles to overcome. Making the gravity work on this sphere would have been complicated, but doable, but then I read that the terrain tools wouldn't work properly and that could be a problem. The last issue that I saw for this, which makes me think that this idea is dead is how strenuous this might be for the systems, since I want the planet to be fairly full of interesting things to explore.

This led me to the idea of a modular system of tiles (if I'm using that term correctly), where I could procedurally generate these tiles, and align them in a spherical shape. I could instantiate and destroy the tiles as needed to preserve system resources, and would make the procedural generation aspect of this easier for me as well (at least I think it will). The problem I see with this model is how to make square (or any other shaped tiles) form a sphere.

I am attempting to build this in UE4. If this is impossible, or at least prohibitively difficult, to do in the engine, then I rather find out now before I get too far along in the project. And any help or resources on how I can do this if possible will be greatly appreciated.


texts: How can I implement gravity? Not for a particular language, just pseudocode...


texts:
Most tutorials for generating glitch art usually has to do with some form of manipulation of the compression of files. Should my goal instead to replicate the look of these glitches in shaders or is it somehow possible to authentically generate the compression artifacts in real time?

Example:

This effect which I'm particularly interested is referred to as datamoshing. It does "things" using the p-frames of a video (frames that I think store just the change in pixels). I feel like I need a better understanding of both graphics programming and data-compression.


texts: SignalR For Multiplayer Game Development

texts: I've been working with SignalR for live chat and notifications in .NET platform and was wondering how much is it worth for working on games development? I've made some jQuery browser games and I want to make them multiplayer. Is there any performance issues if I use SignalR for games development? Need some detailed info about it. Thanks.


texts:
I'm thinking about making a StateManager for my game. I want to know how to design it; that is, how to use a stack to push and pop states onto, and draw them to the screen.

For example, should each State be a JPanel? I want to make a Menu, preferably using JButtons if possible. I don't want to add them directly to the main panel because I don't want to have to constantly add and remove those buttons. Also, not all my states are going to be drawable, since I might have a state that contains a MouseListener to detect clicks.

Right now, I have an empty State class. My Menu class extends from that. My state stack is of the type State. Another design question: if in my Menu I click the "Play" button, should I just say something like StateManager.push(new PlayState()) from the Menu class?


texts: What are pros and cons of Voronoi shatter?

texts:
I have seen some Voronoi shatter videos on Youtube.

What is your experience with it?

What are the pros and cons in time complexity, resource complexity, implementation difficulty...?

Does it emulate how a real material would react?


texts:
I have a celestial sphere with a plane in the centre and spheres (stars) aligned around the centre with a fixed radius.

In order to show the stars visible from a certain latitude and longitude from Earth, I need to rotate the plane accordingly.
To rotate the plane properly, I converted the latitude and longitude into 3D vectors, then utilised the LookAt() method to point the plane at this vector.
The following is the code which calculated the vectors from the coordinates, and utilises the LookAt() Method:
public void positionLand(double latitude, double longitude)
{
    double latitude_rad = (math.PI / 180) * latitude;
    double longitude_rad = (math.PI / 180) * longitude;

    Vector3 markerPositioning = new Vector3();
    markerPositioning.x = (float)-((math.cos(latitude_rad)) * (math.cos(longitude_rad)));
    markerPositioning.y = (float)((math.cos(latitude_rad)) * (math.sin(longitude_rad)));
    markerPositioning.z = (float)((math.sin(latitude_rad)));

    groundPlane.transform.LookAt(markerPositioning);
}

To test if this would work, I used the coordinates of London, UK, latitude: 51.509865 and longitude: -0.118092. And this was the result:

With the LookAt() method changed to the following: groundPlane.transform.LookAt(markerPositioning, Vector3.forward);
This is the result:

Replacing groundPlane.transform.LookAt(markerPositioning); with groundPlane.transform.up = markerPositioning; results in the following:

As you can see, the plane is not properly rotating. Initially, I thought maybe the LookAt() method is using the incorrect forward vector of the plane gameobject, but this isn't the case as there is no connection between the way the plane rotated and the coordinates of London as the plane is near vertical at 89 degrees.
What am I doing wrong and how can I fix this?


texts: Error compiling Unity after porting to mac

texts:
I used BitBucket to move my project from a PC to a Mac, now I can't compile in my Mac, as I get the following error:

Error building Player: Win32Exception: ApplicationName='/Users/josephtripp/Library/Android/sdk/tools/aapt', CommandLine='package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "/Users/josephtripp/Library/Android/sdk/platforms/android-22/android.jar" -F bin/resources.ap_ --extra-packages com.everyplay.Everyplay:com.unity3d.ads.android -S "/Users/josephtripp/sens-rebooted/Temp/StagingArea/android-libraries/everyplay/res" -S "/Users/josephtripp/sens-rebooted/Temp/StagingArea/android-libraries/unityads/res"', CurrentDirectory='Temp/StagingArea'

Any help would be of great use.


texts: Is the Manhattan distance monotonic when used as heuristic function?

texts:
I have a square-based map. Only horizontal and vertical movement is allowed (no diagonals). Movement cost is always 1.

I'm implementing an A* algorithm on that map, using the Manhattan distance as a distance heuristic. Is this heuristic consistent? Can I can avoid checking g(node) against nodes that are in the CLOSED set?

Edit: By consistent I mean monotonic.


texts: Why it’s recommended to keep global variable initialization and the objects’ constructors very simple (C++)?

texts:
Considering  game-development?

I have this question in a gamedev quiz and I wonder what to answer.

Any clues?