texts:
I have a 3D matrix filled with "empty space" where I put some objects (objects are represented as bunch of occupied space).

The bullet is fired from coordinates (x1,y1,z1) at angles (verticalAngle,horizontalAngle).

How do I find the first coordinates in the bullet's trajectory line which is not market as "empty space"?

I suppose I'd have to loop through all the coordinates in that line till I find the not empty one (or the end of the matrix). But how do I calculate what are those coordinates that I have to go through?

When firing a bullet in 2D space I suppose this would be calculated as
y = cos(angle) * x + startPosition where I'd increment x (in a for loop) to get y and check (x,y) cell for objects or "empty". Actually I'd have to increment y in the for loop to get x instead in case the trajectory line is closer to y-axis than x-axis.

But can someone help me with doing this in 3D space?

EDIT:
Well I found this formula: (x,y,z)=(x0,y0,z0)+t(a,b,c) where (x0,y0,z0) are starting points and (a,b,c) direction factors, so I think I could increment t in a loop to get the coordinates.


texts: Character Jump (AddForce) unusual behavior near objects in unity 2D

texts:
My character object has a single jump mechanics and I just noticed the whenever I press the jump button many times quickly in which the character is near a "Platforms like staircase, boxes or even sometime near the edge of a platform (while also being up in the air and pressing jump many times when colliding)" it starts to fly off beyond my jump force. Can anyone help me to fix the physics? Thanks!
My Jump system code sample:
Rigidbody2D mybody;
public float jumpforce;
public bool isGrounded = false;
public Transform feet;
public LayerMask groundlayers;
public float groundradius = 1f;
bool Jumprequest;

void Start () {
    mybody = GetComponent<Rigidbidy2D>();
}

void Update () {
    JumpRequest();
}

void FixedUpdate() {
    Jump();
    JumpOptimization();
    isGrounded = Physics2D.OverlapCircle(feet.position, groundradius, groundlayers);
}

public void JumpRequest() {
    if (CrossPlatformInputManager.GetButtonDown("Jump") && isGrounded) {
        isGrounded = false;
        Jumprequest = true;
    }
}

void Jump() {
    if (Jumprequest) {
        mybody.AddForce(new Vector2(0, jumpforce) , ForceMode2D.Impulse);
    }

    Jumprequest = false;
}

void JumpOptimization() {
    if (mybody.velocity.y < 0) {
        mybody.gravityScale = Fallmultiplier;
    }
    else {
        mybody.gravityScale = 1;
    }
}

Here is a sample picture that might help:
The red line shows when character collided with an object while addforce is added upwards and pressing
Jump button repeatedly at the same time, the character flies off beyond my jump force.


texts: In XNA, is there an issue with copying/pasting the using statements to each .cs file?

texts:
When I'm working on a project in XNA I copy the using statements from file to file. However, on tutorials I've seen for various games, they show files that only have specific using statements used. Do the other statements cause problems in the event the program doesn't need it?

I want to avoid any future problems.


texts: Isometric Tilemap is blocking UI elements

texts:
I'm using Unity 2019.4.6f1, and I'm working on Isometric Tilemaps.
The hierarchy is like this:

The VillageScreen is a Canvas, img-bg is an UI Image, the two Panels are UI Panels, and the Grid and two Tilemaps are the isometric tilemaps. The problem is, the Grid & Tilemap is blocking all other UI elements, and it seems to be always on top, no matter how I set the Z value.
The Grid setting is:

And the Panel setting is:

My question is: How do I put the UI elements ABOVE the Tilemap?
p.s. the UI button is clickable, it just cannot be displayed properly.
--
UPDATE: Added a mockup screen - Black circles are buttons, while Red texts are UI texts for displaying scores.


texts: cocos2d-x - object creation and management in game design

texts:
How do others keep track of everything going on in their games? I am working on a new game and I am quickly realizing everything that I need to keep track of.

Example:

Maybe a layerManager that keeps track of all the layers and what is happening for a particular scene.

Maybe a sceneManager for sharing objects among scenes

But then getting to game play itself, what if you have 100 objects on the screen each with its own state and happenings, there needs tobe a way to keep track of all of that.

Drawing everything out is really helping me.

Can anyone share with me how they go about object tracking/management? I am seeing a few different managers and then maybe even a parent object that manages the managers..is my thinking way off?

Any design patterns that may be useful for me to read about?

Update: doing some reading and maybe a Factory pattern might apply.


texts: Xna - How do you use large animations for a menu

texts:
In the main menu of my game I have several animations that pause in specific frames.

I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames...

How can I play these large animations? I tried video playback but I couldn't find a way to do this...


texts: Resource streaming with job threading system

texts:
I am currently researching resource streaming for my current game engine. To add a bit of context, I am doing a contiguous world for a Baulder's Gate style CRPG. So while the camera is usually looking downwards at an angle... it can be rotated and lifted up and down to compensate for mountains.

That means for vistas, it needs to be reasonably decent. At least with an added advantage that there will probably be very few unique assets that will be loaded in every terrain cell. (currently each cell is about 60m).

Most of the research I found turns up to have a separate thread for loading in assets. I can see how that works, as obviously holding such a thing on the main thread could introduce stalls.

But... currently my architecture is the main thread which has rendering and gamelogic. Then the rest are just worker threads for a job system.

I planned on moving the Rendering system off of the main thread, which means that on a common consumer PC (4 threads) I have two fixed threads... and two worker threads.

Moving a loader to it's own thread would basically reduce performance on some update cycles to a single threaded update.

My main thread is controlled by lua, and low level systems are in C++. Lua dispatches low level jobs only (Physics first, Animation updates, Transform updates, dispatch to renderer), and waits for them to finish before continuing to the next job dispatch, as certain data requires information from the previous component updates.

Annd... one recommendation I ran across, (because I am only targeting PC for now) was to keep data about each cell on the memory. Such as transforms, skeleton handles, material handles, etc.

So... I have a few questions. How well would a resource streamer work if each loading call was dispatch to a job as it is needed? From my research, I found multiple people stating that multiple async loading could slow the disk drive down.

What would be a few effective strategies for resource streaming? I know that it's better to have everything in one file, like a zip instead of scattered about folders. But I could never find any straight answers. One google search said to cut the file up into equally sized bits (which sounds logically stupid in my opinion.) another was priority loading, which sounds pretty reasonable. I understand this question is pretty vague, but finding answers in general in a world dominated by pre-built engines is already difficult enough.


texts: How can I prevent pinching and jagged edges when deforming joints in 3ds Max?

texts:
I've rigged and skinned a character, but no matter how or how much I blend the weights, it doesn't look good:

Why does the weight map look pixelated? I don't get it. I've never been able to get past this point when animating. I don't think it's a model resolution issue, since as you can see in the picture, the model is quite detailed.

How can I prevent the indicated problems?

Here are some reference images of my wireframe and weight maps:

EDIT

After recreating a model entirely to try and have another go at this, Ive found that my new model is repeating the previous outcome. Here are some images

enter image description here


texts:
I am entirely new to programming. Recently just watched this YouTube tutorial and follow the way the author wrote the code until (1:22:24). I'm not sure why the scene reset function for trasnform.position.y > 10 not working for me. The compiler does not detect any error and game run as normal but the scene does not reset when the bird position on y axis more than 10. I'm using another bird object anwyay since i can't find exactly the same bird picture as author did. Also is there a way to check what the value store in each variable?  Example I want to check what the value stored in "transform.position.y" to find out why it is not working.
using UnityEngine;
using UnityEngine.SceneManagement;

public class GreenBird : MonoBehaviour
{
    Vector3 _initialPosition;

    private void Awake()
    {
        _initialPosition = transform.position;
    }

    void update()
    {
        if (transform.position.y > 10)
        {
            string currentSceneName = SceneManager.GetActiveScene().name;
            SceneManager.LoadScene(currentSceneName);
        }
    }

    private void OnMouseDown()
    {
        GetComponent<SpriteRenderer>().color = Color.red;
    }

    private void OnMouseUp()
    {
        GetComponent<SpriteRenderer>().color = Color.white;
        Vector2 directionToInitialPosition = _initialPosition - transform.position;
        GetComponent<Rigidbody2D>().AddForce(directionToInitialPosition * 100);
    }

    private void OnMouseDrag()
    {
        Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(newPosition.x, newPosition.y);
    }
}


texts: Neverending game development: how do I finish my game?

texts:
I have started developing my first iPhone game with Cocos2D in May 2012 after quitting my job as Bioinformatician in an important research center. Before quitting I spent six months studying some basics of Objective-C and Cocos2d. I moved back to my parents place leaving an important relationship in a different country and leaving all my friends and "social life" there.

Since then I stayed "locked" (trying of course to build some social life and to have healthy daily walks) in my room developing a game for iPhone. Has been more than a year now and I haven't finished yet. I spent a big big sum of money in graphics and music and involved lot of people that are now waiting for the release. They keep asking "when will you finish?" and I say "I am nearly there". The reality is that I "think" I am nearly there but then I have bugs to solve and thing I thought would take a week to develop take 2 weeks or more (the Pi greek rule..).

The reality is that I am fed up with coding. If I was coding with 100% of focus and motivation I could probably finish it in little time but I see that my performance are quiet weak in this period.

I start to feel depressed as soon as I start coding. I have been away from keyboard for two weeks and I felt like getting back to real life. Now that I am back coding with only my screen on the horizon I feel like that I really have to finish and that to do so I have a neverending mountain still to climb. Bugs to solve and more importantly some bits of the game structure still to implement.

It feels like being on top of the Everest, with no oxygen and a small invisible path to follow.

My questions:

Anyone there that felt the same?
Any advice (apart of "keep calm and carry on")?


texts: Doom-style 8 directions sprite math HELP C++

texts:
I'm trying to get Doom-style 8 direction sprite rotation that changes its sprite depending on the camera and the forward vector of the entity just like this video here: https://www.youtube.com/watch?v=DBRR_ZVWtMk&t=13s.

I've searched around the internet for a solution and I have found some people that have been having the same issue but no one that really got it working like it should. I managed to figure out how to get the entity to change it's sprite depending on the camera view angle but I can't figure out how to account for the entity's own forward vector. I would assume you'll use the CrossProduct but I'm not sure...

Here is my code:

// Get the angles
angles = entity->parms.axis.ToAngles();

// Compute the forward and normalize
forward = angles.ToForward();

// Compute the direction and normalize
direction = rg.renderView.origin - entity->parms.origin;
direction.Normalize();

odVec3 point = forward.Cross(direction); (NOT USED)

// Compute the yaw angle
yaw = RAD2DEG(odMath::ATan(direction.y, direction.x));
yaw = odMath::AngleNormalize360(yaw);

        if (yaw >= 22.5f && yaw < 67.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_1");
        else if (yaw >= 67.5f && yaw < 112.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_2");
        else if (yaw >= 112.5f && yaw < 157.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_3");
        else if (yaw >= 157.0f && yaw < 202.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_4");
        else if (yaw >= 202.5f && yaw < 247.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_5");
        else if (yaw >= 247.5f && yaw < 292.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_6");
        else if (yaw >= 292.5f && yaw < 337.5f)
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_7");
        else
            entity->parms.skin = R_FindSkin("skins/sdk/rotation/angle_0");


texts: How to correctly generate tile map with atlas in cocos2d-x (4.0) without TMX file?

texts:
Good afternoon!
Can someone give me advice, what is the proper way to generate TileMap?
I know about TiledMapTileLayer in LibGdx. With that tool i could set tile map cell by cell, something like this:
TiledMapTileLayer.Cell cell = new TiledMapTileLayer.Cell();
cell.setTile(new StaticTiledMapTile(splitTiles[(int)cellCoordinates.x][(int)cellCoordinates.y]));
cell.setFlipVertically(tileInfList.get(i).isFlipVertical());
cell.setFlipHorizontally(tileInfList.get(i).isFlipHorizontal());

So algorithm was like this:

I parsed my "custom" xml file with map properties (not TMX), such as position of tile in image atlas and position in game world.
I created new TiledMap() and TiledMapTileLayer.
Added cells to a layer. Than render layer.

But can Cocos2d work with tiles in such a way? Or i should create individual sprite for this purpose (like cells in LibGdx)?
What is the best way to positioning and create map if you have an atlas and xml file with map properties?
<TileMap defaultScale="1.0" image="img/love_island_atlas.png" maxScale="2.0" minScale="0.25" tileBorderSize="2" tileHeight="100" tileMapHeight="2700" tileMapWidth="3400" tileWidth="100" tilesPerAtlasColumn="4" tilesPerAtlasRow="4">
  <items>
    <list>
      <Tile flipHorizontal="false" flipVertical="false" height="100" index="1" width="100" x="480" y="-1136"></Tile>
      <Tile flipHorizontal="false" flipVertical="false" height="100" index="10" width="100" x="2080" y="464"></Tile>
      <Tile flipHorizontal="false" flipVertical="false" height="100" index="1" width="100" x="3780" y="-1036"></Tile>
      ....
    </list>
</items>

Thank you guys!


texts:
I'm setting up a basic mario-like 2D platformer and I'm trying to give 'enemies' a patrolling path on a platform. (just like the turtles in Super Mario Bros). All they do is patrol from left to right and back. <--->

Currently my game object is walking to left and right in the middle of my scene.
Despite me positioning my game object as far left as I can, at first it walks to the center of the scene and continues acting out his patrol in the center of my scene.

What I can't seem to figure out is adjusting the position where he patrols. I don't want him to patrol in the center of the scene.

I think I should use the originalX position in the Update function but I'm not sure how (I could be wrong)?

This is the script that is linked to my enemy gameobject.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {
    public float walkSpeed = 1.0f;      // Walkspeed
    public float wallLeft = 0.0f;       // Define wallLeft
    public float wallRight = 5.0f;      // Define wallRight
    float walkingDirection = 1.0f;
    Vector2 walkAmount;
    float originalX; // Original float value

    void Start () {
        this.originalX = this.transform.position.x;
    }

    // Update is called once per frame
    void Update () {
        walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;
        if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
            walkingDirection = -1.0f;
        } else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
            walkingDirection = 1.0f;
        }
        transform.Translate(walkAmount);
    }
}


texts: Which Swing control should I use to render graphics with?

texts: I'm using the Swing UI toolkit in Java, and I want to use the Graphics class to draw images and grids in a control. Which is the most appropriate control for this?


texts:
I'm constructing a Body (a box2d body using AndEngine) using multiple Fixtures and later I need to get the world position of these Fixtures.

Currently I am trying something like this;

// Declarations
Body body;
Fixture centerFixture;
Fixture leftFixture;
Vector2 centerPos = new Vector2(0, 0);
Vector2 leftPos = new Vector2(-1.5f, -1.5f);

void setup() {
  BodyDef bodyDef = new BodyDef();
  bodyDef.type = BodyType.DynamicBody;
  bodyDef.position.set(new Vector2(10, 10));

  body = physicsWorld.createBody(bodyDef);

  PolygonShape centerShape = new PolygonShape();
  centerShape.setAsBox(1, 1, centerPos, 0);
  FixtureDef centerDef = new FixtureDef();
  centerDef.density=1;
  centerDef.shape=centerShape;
  centerFixture = body.createFixture(centerDef);

  PolygonShape leftShape = new PolygonShape();
  leftShape.setAsBox(0.5f, 0.5f, leftPos, 0);
  FixtureDef leftDef = new FixtureDef();
  leftDef.density=1;
  leftDef.shape=centerShape;
  leftFixture = body.createFixtureleftDef);
}

void someFunction() {

  Transform transform = body.getTransform();
  Vector2 temp = new Vector2(leftPos);

  // These two seems to not be the center of the fixture
  Vector2 worldPosition = transform.mul(temp);
  Vector2 pixelPosition = new Vector2(worldPosition.x * PhysicsConstants.PIXELS_PER_METER, worldPosition.y * PhysicsConstants.PIXELS_PER_METER);
}

But is seems that as the body rotates the worldPosition is off.

How do I get the world position of the Fixture?


texts:
I have this problem where I split my big world into chunks and I don't know how to draw it into my game camera's view. Each world chunk has its own coordinate system, so when object reaches border of one chunk and steps into another - coordinate system resets to zero. For example from world_x = 1440 into world_x = 0.

To draw only those objects that are in the camera's view, I use code:

int screenX, screenY; //screen position of the object being drawn

screenX = object.x-camera.x;
screenY = object.y-camera.y;

The problem appears when camera sees two different chunks. Lets say camera's coordinates are:

screenX = 567
screenY = 0

My drawable object is at

world_x = 1266
world_y = 0

In this case object's screen coordinates are (x)699, because screenX = object.x-camera.x. But what if camera stays in the same place and object finally reaches different chunk. Object's coordinates are reset to zero. That means that its screen coordinates becomes (x)-567.

That screen coordinates conversion would work if I would be doing non partitioned game world, but now it don't. Any ideas?


texts:
I wonder what technology applications like Xara3D use to be able to perform real-time ray tracing.

How is such good quality rendering done in real-time?


texts: Nvidia High Performance Processor Setting leads to graphical bug (Seizure Warning) with current lighting system, drawing completely in the shader code

texts: I followed the Lighting tutorial on learnopenGL, modifying some of the code to work in a 2D game engine. Everything was looking great and my team got our game done and the lights were quite simple for our designers to use. However we ran into a rare bug. as shown here: https://www.youtube.com/watch?v=to0mMP5I0cs one team member was able to recreate the bug by switching his Nvidia settings to use the "High Performance Processor" as opposed to "Integrated Graphics". Otherwise everything renders properly. The bug doesn't appear when there are no lights and everything is rendered in its full color. We have gone through alot of Ideas already but they haven't worked and now I am at a loss. Does anyone have any ideas about what is going on?


texts: Render object with different shader depending on the camera

texts:
I have an object with a custom shader. When it is being rendered by cameraA, then I want it to render a particular way (ex red). When it is rendered by another cameraB, I want it to render a different way (ex green).

Is there some way I can tell what is the current camera rendering in the shader? Or perhaps I can toggle a boolean value in my shader between rendering of each camera? Where would I do this (OnPostRender() maybe?).


texts: How much latency can I expect from Apple Game Center connections?

texts:
I would need a few bytes of data roughly every 0.1 seconds between players to have a smooth multiplayer snake game on iOS.

Is the iOS Game Center fast enough for this? What latency values can I expect?


texts: Color spaces: Should colors be converted to linear color before applying premultiplied alpha?

texts:
For instance, when loading an image that is SRGB, which of these is correct?

Simple premultiply:

Take SRGB color from file and multiply RGB by alpha

or

Convert to linear before premultiply:

Take SRGB color from and convert RGB to Linear
Multiply Linear RGB by alpha
Take Linear RGB and convert back to SRGB


texts: Does Minecraft Really Rely on CPU More Than GPU For FPS?

texts: I understand that Minecraft runs on Java which is very demanding on the CPU (garbage collection and JVM processes), but I still don't understand how FPS is the CPU's responsibility. Shouldn't the CPU handle game logic while the GPU handles rendering the results of that logic asynchronously? Minecraft was developed using OpenGL libraries afterall. But I still see a ton of people saying that upgrading your CPU is more worth it than upgrading your GPU if you want good FPS on Minecraft. What's actually happening under the hood?


texts: Continuous weighted random distribution, biased toward one end

texts:
I am currently contributing to a particle system for our game and developing some emitter shapes.

My uniform random distribution along a line or along a rectangular area works fine - no problem.

But now I would like to have something like a 1 dimensional gradient in this distribution.
This would mean for example lower values are more common than higher values.

I don't know what would be appropriate mathematical terms for this problem, so my search skills are rather useless with this one. I need something that is computationally simple, as the particle system needs to be efficient.


texts: Compiler cannot find some DX11 types (but can find DX10)?

texts:
my problem is probably trivial but I'm new to DX and have some trouble. I've found a code snippet (of a Shader class) with ID3D10Effect and ID3D10EffectTechnique types but I'm using DX11 so I changed these to ID3D11Effect and ID3D11EffectTechnique. But the compiler protested saying that it doesn't know such types. I thought: "maybe there aren't such types actually" but quick google search indicated otherwise. I cannot find any information on which header they're in, though.

So which one is it? I've also found out that there used to be a header called d3dx10math.h but there's no d3dx11math.h. Why is that? Are there any other headers/types abandoned in DX11?


texts: How can I create click and drag for a 3D Jenga game in Unity?

texts:
Essentially, I am trying to create a game that mimics Jenga. Right now I have made it so that the blocks collide with each other and have gravity, everything works very well. The one thing that I am missing is the ability to click on a block and drag it out of the tower. I am using C# on Unity 3D. I am not the best at programming myself, so I used some other code and it ended up not working.

using UnityEngine;
using System.Collections;

public class mouseDrag : MonoBehaviour
{
    public GameObject Cube;

    float distance = 10;

    void OnMouseDrag()
    {
        Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
        Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);

        transform.position = objPosition;
    }
}

The name of the Jenga piece is called "Cube". I am not sure if I used the:

public GameObject Cube;

correctly in this instance. Also, right now I have a single Jenga piece but will need many more in the end. Does that have an effect on the code? Does the object name even need to be referenced at all? I am looking for a way that my mouse click could move any object with physics in the game.

When I run the game, everything seems fine, however as soon as I click and start to drag on the Jenga piece it gives me this error.

  NullReferenceException: Object reference not set to an instance of an object
  mouseDrag.OnMouseDrag () (at Assets/mouseDrag.cs:12)
  UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

This game will eventually be made for mobile devices.


texts:
I'm trying to implement "sliding" movement on a simple grid, where the movement vector is continuous (floating point direction) but the grid is discrete (boolean blocked or open on integer axes).
The "destination" tile is found by adding the rounded movement vector to the current tile. That part is naive and works well enough.
For example, here:

blue is the current (source) tile
the yellow arrow is the movement vector
green is the destination tile

But this movement ends up being restrictive and I'd like to enable "sliding" to approximate player intent. My goal is that if the destination tile is blocked, the "next best" tile is used instead, provided it is available. I don't know how to calculate that.
As you can see, the naive destination tile (where the yellow arrow lands) is blocked. As a result, I'd like to pick the green tile above as the destination tile.

However, crossing a diagonal should be allowed either, so the following case should result in the movement being blocked:

Finally, I'd like this algorithm to be as permissive as possible, so even the smallest component of the movement vector could win if no better alternative is found. For example, the movement should carry upwards in that case:

This sounds like a fairly simple problem and there may be existing algorithms for it, but I don't know what it's called, so I'm having trouble finding resources on it.


texts: Correct utilisation of gameloop (Android)

texts:
When using a gameloop like (much simplified)............

updateLogic();
render();

How does one perform 'single' operations?  I mean, things like triggering sounds (which will only be played once), displaying a 'Get ready' graphic at the start of the game etc...

Currently I'm simply using 'flags' so maybe something like: (Pseudo code)

if(gameNotStarted==true)
display getReady;

This does work, but I end of up with a ton of condition checks in my game Loop.

Being that I can't just stop the game loop (I can't right?) every time I want to perform a single operation, is what I'm doing the correct way or is there something that I'm missing?

Another example might be when a player completes a level.  I want to stay within my class/activity (I.E., the game as a whole is contained within one activity), then I move onto a small 'cut scene' which simply displays 'Well done' and plays a little piece of music, before returning to the next level of the game.

How would one handle that situation, again remembering that I'm not starting a new activity for each level (if I did, I could see that being a nightmare to manage).


texts: How do I get the coordinates of a rotated shape in SFML?

texts: I am trying to get collisions of bullets working, and am using SFML. I am using code to get the position of the points of the rectangle for collisions, however I think there's a way to do this without having to get points but by simply getting the points from SFML, since the shape is a rectangle and the points are stored in that way. Is there a way to do that? Through a combination of getPoint() and getGlobalBounds() maybe?


texts:
I am making an iphone opengl es 1.0 game. I am using a fixed timestep with interpolation on the end. One thread only. I am using CADisplayLink to fire the game loop.

First question: is it okay to use CADisplayLink to fire the game loop? i am targeting > 3.1 so that's not an issue.

Real question: What's the proper way to handle user touch input as it relates to my gameloop and adding state to my game. For example lets say when the user touches the screen i want to fire a bullet. I've read that I don't want to actually update my game state in my touch handler function. But I should instead record that touch in an array or something and then on the next gameloop update(dt) i go through the array and updated my game state based on the array items.

is this correct? shouldn't i be storing a timestamp of each touch so i know exactly how to inject it into my game?


texts: Don't know what to do with XML file and Spritesheet (Swift 3)

texts:
I'm new to spritesheets and game development in general. I have two files:
1) a .png spritesheet with tons of sprites and
2) a companion XML file with coordinates, anchor points, image names, and animation info.

The spritesheet appears to have no order, and I cannot make sense of the organization of the XML file (which does not appear to contain the dimensions of the seemingly different-sized sprite images)

My question is: How do I use these to make sprite animations? It appears the work has been done for me, but I have no idea how to use it.

In particular, I would like to use this with Swift 3 SpriteKit.

I would be satisfied with exporting all the sprites into separate images with the appropriate names. Is that possible? Thank you for your help!!


texts: How to adapt to using a graphics library in a game coded using Java's native graphics methods?

texts:
I've spent months coding a game that uses Java's native graphics methods to create a polygon-based 3D engine, and at this point it's about 12,000 lines long. However, the graphics performance is starting to get bogged down and is wildly inconsistent (e.g. running it on my very nice windows laptop gets me only around 10 FPS, and running it on my Macbook Air gets me around 30-40). From what I've read, Java's graphics are not optimized for speed as much as they would be had I used a library created to aid in drawing efficiency. Given how much work I've put into the project without knowing I probably should be using a graphics library to speed my game up, how easy would it be to implement LWJGL to my game? And if that were difficult, are there any libraries I could use instead that would make transitioning easier and would boost performance and/or at least make the frame rate more consistent across different systems?

Thanks.


texts:
I am trying to wrap my head around some concepts in a side project I'm working on. I'm struggling with how I can calculate a vector based on my character movement logic. Here are the relevant details of my character movement:

The character's hit box for collisions (and map position validity) is defined as a rectangle: x,y,w,h
A character can move in 8 directions, let's keep this simple to ignore strafing, call this direction:

Left(x-1), Right(x+1), Up(y-1), Down(y+1)
UpLeft(x-1,y-1), UpRight(x+1,y-1),DownLeft (x-1,y+1), DownRight(x+1,y+1)

The character can be in two moving states, again keeping numbers simple:

Walking 1 x offsets
Running 2 x offsets

When a character is moved the following logic happens:

Create their proposed new hit box by adding an offset to their x & y coordinates based on their direction, call this proposedHitBox
Check if the proposedHitBox is a valid position on the map, if so, then update the character's position to the location defined on the proposedHitBox
If the proposedHitBox is not a valid location on the map it should try to glance the character. This is where I'm having trouble.

Given all this, how do I essentially, calculate a vector of their proposed motion?

Example:

Character is at 10,10.
Character starts running.
Input is DownLeft.
Proposed location is 8,12 (x-(1x2),y+(1x2)).
Proposed location is valid.
Update character position to 8,12.
What calculation defines my vector? How does magnitude come from this? Is that generally stored as Z in a 2D game? So I'd use a Vector3 to store it? How does velocity come into this?

I'd assume my vector is a 45deg angle from current to proposed...?

Edit

Here is a picture of what the walls can look like in the game. The red box being the hit box as discussed above. The character is bound inside the blue polygon (which represents outer walls). Black being inner walls. The way I was doing glancing was overlaying 4x4 tiles across this entire map and then for each tile that the character should glance on I would choose an incoming direction (i.e. DownLeft) and then redirect them to a different direction (i.e. Down) which should make the proposed hit box in a valid position. This is however very tedious as I have to create glances for multiple directions for every tile. I'm looking for hopefully a better way.

I was reading that you could add vectors to each tile but I'm not sure how this works because on some tiles a incoming direction does not always have the same out direction.


texts: Is there a way to squash/stretch a sprite based on an angle?

texts:
I have a ball that can move along any angle, and I want to squash and stretch it based on this angle.
To be clear, if you dropped the ball down at a -90 angle, the squash would be all along the y, and the stretch on the x.
This wouldn't work however for a 0 degree angle, where the squash is on the x, and the stretch on the right.

Is there a way to generalise this into an equation?


texts: Trying to set up a planting and harvesting system, but it only works in one trigger area?

texts:
What I want to happen is when the player presses alt, some time passes and an object is instantiated there. I also want it so that the player can't instantiate another object there until they've collecting the one they've planted there already. This is working when I only have one planting area, but once I have more than one planting area it no longer works- for some reason I'm only able to keep planting and collecting in just one of the trigger areas instead of all of them. What am I doing wrong?

public bool instantiated;
public bool inside;
public bool collected;
private IEnumerator coroutine;
public GameObject powerorb;
public Material[] material;
Renderer rend;

void OnTriggerStay2D(Collider2D Collider2D)
{
    if (Collider2D.gameObject.tag == "Player")
    {
        if (instantiated == false)
        {
            inside = true;
        }

        if (collected == true)
        {
            instantiated = false;
            collected = false;
            rend.sharedMaterial = material[0];
        }
    }
}

void OnTriggerExit2D(Collider2D Collider2D)
{
    inside = false;
}

    // Use this for initialization
void Start () {

    rend = GetComponent<Renderer>();
    rend.enabled = true;
}

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

    if (inside && Input.GetKeyDown(KeyCode.LeftAlt))
    {
        StartCoroutine("spawning");
    }

    if (instantiated == true)
    {
        StopCoroutine("spawning");
    }
}

IEnumerator spawning()
{
    rend.sharedMaterial = material[1];

    yield return new WaitForSeconds(8);
    Instantiate(powerorb, transform.position, transform.rotation);
    instantiated = true;
    inside = false;

    yield return null;

}

I reference if the object has been collected in another script with this:

 if (collecting)
        {
            GameObject.FindWithTag("PowerFarm").GetComponent<PowerFarmCoroutine>().collected =
        true;
            Destroy(gameObject);
        }


texts: how to set up health bar rect that depends on health?

texts:
I need some help with game math.

What I am using:

I am using java awt library.

What I am trying to do:

I am trying to build enemy health bar, which will display as an rectangle. I am display two rectangles. First one is black rectange and it will act as in base container. 2nd one is red rectangle and it will act as helath bar.

now the max size of enemy health bar will be enemy.getWidth(). I need some help with 2nd red rectangle width. how can I set up so that it dependents on enemy.getHealth() and max is enemy.getWidth.?

and enemy.getHealth() will be 4.

Code:

    g.setColor(Color.black);
    g.fillRect(enemy.getX(), enemy.getY(), enemy.getWidth(), 5);
    g.setColor(Color.red);
    g.fillRect(enemy.getX(), enemy.getY(), enemy.getHealth() * 4, 5);


texts: Reading data from files in Unity on Android

texts:
I have successfully read in and written level data using .dat files on unity PC builds, but compiling for android stops me from being able to read in information from the resources folder. I was under the impression that when it's compiled the resources folder was still accessible? I could create a .dat file in the persistent data path but that means hard coding the information only to serialize it, rather than the data originating from the .dat file itself. How can I include this data within the apk without hard coding it?

Here is my code, working on PC:

    Stream file = File.Open("Assets/Resources/levelData.dat", FileMode.Open);

    levelData = (LevelDataFile)bf.Deserialize(file);

    file.Close();

Edit: for context, the level data is very simple as this is just a puzzle game, and each level will just have a few starting positions and obstacles etc, and there will be 100+ levels, hence I'm not doing a scene per level.


texts:
In all of the code samples that I have looked at, the game loop looks something like this:

while(true)
{
   InputAndUpdate();
   Draw();

   SwapBuffers();
}

However doesn't this destroy parallelism between the CPU and the GPU? After the swap buffers call, the GPU will be sitting there idly while the CPU is handling input and updating. Then when the CPU has finished issuing draw commands, it waits until the GPU is finished rendering.
Why isn't it done like this? :

while(true)
{
   Draw(); //First issue the draw commands
   InputAndUpdate(); //Update while the GPU is busy rendering

   SwapBuffers(); //Now block and wait for the GPU to finish
}


texts: How do I properly use multithreading with Nvidia PhysX?

texts:
I'm having a multithreading problem with Nvidia PhysX.
the SDK requires that you call Simulate() (starts computing new physics positions within a new thread) and FetchResults() (waits 'till the physics computations are done). Inbetween Simulate() and FetchResults() you may not "compute new physics".

It is proposed (in a sample) that we create a game loop as such:

Logic (you may calculate physics here and other stuff)
Render + Simulate() at start of Render call and FetchResults at end of Render() call

However, this has given me various little errors that stack up: since you actually render the scene that was computed in the previous iteration in the game loop.

Does anyone have a solution to this?


texts: Is flowchart correct way to visualize gameplay?

texts:
I made the following flowchart in draw.io. it's just a simple arcade shooter. cardboard zombie pops up, bang, or not. I don't have any official education in game production.

So, are there other chart styles, or UML diagrams that would be better suited for drafting this type of simple game play?


texts: How to either draw a group of tiles completely behind or completely in front of a player?

texts:
Say you're rendering a 2D top-down tile map and there are some objects in the tile map that the player should be "in front" of when below them, and "behind" when on top of them. Like in this example screenshot:

This works because the player is on layer 1, the top two tiles are on layer 2, and the bottom tile is on layer 0.
Let's say in this example that the object has no collision. If the character then walks up, then the character will be half-in-front and half-behind, like this:

The reason why this is a problem is because with tiles, they don't really have a concept of state. If the 3 tiles were part of the same "object", then this wouldn't be a problem, because we could just render the entire group of 3 tiles as a single sprite, and then sorting could be done, and the entire sprite could be rendered behind or in front of the player.
However, with tiles, this knowledge isn't known, as they are purely decorative numbers.
One possible solution is just to instead forsake tiles for these sorts of objects, and force them to be entities in the game itself as opposed to just tiles, but because there can be many of these, that would be a performance hit. It also complicates the logic.
Is there any better solution?


texts: Rigidbodies gaining speed when they shouldn't

texts:
I'm trying to get the effect of a constant magnetic field on a charged particle. A really important aspect of this is that the magnetic field doesn't do any work on the particle, which in this case means that it doesn't make it any faster or slower, just changes its direction.

On paper, this works because the equation for magnetic force on a charged particle is q*VxB, or the cross-product of the velocity of the particle and the magnetic field times the charge of the particle, which makes the force always perpendicular to the velocity. The code I wrote for this is this:

forces += charge * Vector3.Cross(rb.velocity, cons.constantMagneticField);

If the particle is the only thing that exists, and it has some initial velocity, and the magnetic field is perpendicular to that velocity, then the particle should ideally move in a circle of constant radius, because the magnetic force will always be perpendicular to the velocity. With what I have now, my particle moves in a tightish spiral, gaining speed way faster than I'd expect it to, and at a rate that scales with the particle's velocity.

Is there a way to compensate for this? If not, is there a another way to get the behavior I want?


texts: Choosing the correct network protocol for my type of game (its Wc3 Warlock style)

texts:
I need to code a little game for a school project.

The type of the game is like the Warcraft 3 map "Warlock", if anyone doesnt know it, here is a short description:
up to ten players spawn into an arena filled with lava, the goal of each player is to push the other players into the lava with spells (basically variations of missiles, aoe nukes, moba spells etc)
http://www.youtube.com/watch?v=c3PoO-gcJik&feature=related

we need to provide multiplayer-support over the internet, for that reason I am looking for the best network protocol for this type of game (udp, tcp, lock step, client-server...)

what the requirements are:
- same/stable simulation on all clients
- up to ten players
- up to ~100 missiles on the field
- very low latency since its reaction based (i dont know the method wc3 used, but it was playable with the old servers)

what would be nice (if even possible, since the traffic might be too big):
- support for soft bodies over the network (with bullet physics), but this is no real requirement

I read several articles about the lock step method used for RTS games, this seems to be great, but does it fit for real-time action games too (ping-related)?

If anyone has run into the same problems/questions like me, I would be very happy about any help


texts: How to let a gun follow the camera while characters hands are following the gun

texts:
I have made a character using MakeHuman, imported to blender and created a view animations. Then I imported the character as .fbx file into Unity. I set up an FPS scene with a player holding a gun in front of him. The camera is inside the character's head and the character is inside a capsule which is the actual movement controller. I basically just set the parent as needed. So if the gun should follow the hand I make the hand to be parent of the gun in the hierarchy.

I want the gun following the camera, so it is pointing exactly at the center of the players view where a crosshair is positioned.

But when I let the gun follow the camera, I can't let the hands follow the gun. And if I let the hands follow the gun, I can't let the gun follow the camera.

Is there some logical error in my mind or is this a common situation to find some individual method?


texts:
Take a look at the picture.

I've got a camera(brown) and its ray(red). As I know ray has a direction and unlimited length(if you don't set it yourself). But now I need to determine ray's vector that starts at camera point and ends when it crosses a floor. How can I do that?


texts: How to load textures at other times than startup in XNA using vb.net?

texts:
I've encountered a problem with my game project lately. When I load more than a certain number of textures (around 1000) at startup I recieve an error regarding memory, because I have to use 32-bit in XNA. I am self-taught and so have only basic knowledge of the "correct" ways to program a game. The project itself is getting very big and although I try to compress images together etc, I will have to use more than 1000 textures throughout the project.

My question is this: How can I load textures at other points of time than at startup in XNA, using vb.net? (I'm not using classes at all that I'm aware of, so I hope to stay away from that if possible)


texts: How to handle equipment on a 3D animated character

texts:
Im working on a 3D engine in Java using OpenGL. Animated models are set up and working by transforming vertices based on joint weights in the vertex shader, i think this is common practice.

I am now trying to figure out how to manage equipment that can be worn or carried by a character, like armor and weapons. How is this commonly done, or whats the best way to do it?

Im imagining that you make some sort of attachment point for weapons on the character model, but since that all happens in the vertex shader, how do you go about that? Would you "intercept" the joint transformations and render the weapon independently? Also, how do you find out what the attachment point for the weapon is? Im using a collada file loader to parse .dae files for models and animations, can you somehow "index" bones with special attributes in Blender/other 3D programs?

And for armor: Since armor has to not just move with the character but also stretch and deform with him, do you somehow merge the models, or overlap them?

Im really in the dark about the practices for this but i can't find anything comprehensive on the internet that explains it.


texts: Is there a game not using meshes for models?

texts:
Traditionally, models consist of lots of vertices connected by triangles. That forces the use of a high amount of vertices for detailed  organic shapes or makes models kind of blocky. Even though polygon models can be smoothed by subdivision algorithms, this slow, not that exact or still needs a lot of vertices.

Instead, models could be represented by 3 dimensional splines, bezier patches, nurbs or something similar. This way, we would gain perfectly detailed models instead of blocky one with much less vertices. I am not an expert but I assume that a spline could be even rendered faster than its polygon representation. To make the such mathematically perfect shapes more detailed, we could use displacement mapping.

The only big challenge I can see is projecting those splines in the correct perspective. We can simply multiply all vertices with a projection matrix since they are not connected by straight lines. Instead the parameters of a curve must be modified to fit another perspective. I am not sure if there are mathematical straight forward ways to do this.

Are there games using the latter approach?


texts: Equalling the rotation of an image with its object. Box2dweb

texts:
I have some hard time making the rotation of an image equal to the rotation object that the image belongs to. Simply put it, I don't know how to do it properly but i am not asking for a how-to guide but for some tips/hint and/or infos that i am not aware of...

I was able to align perfectly the image with the object, and so if the object moves in a linear fashion the image is at all times on top of the object and everything is smooth and perfect.
But how is it possible to make the rotation of the image be the same as of the object it belongs to.

No-matter what i tried it is always somewhat off or the rotation of the image behaves weird when in the end the object stops rotating. I tried using using GetAngle(), GetAngularVelocity(), combinations of both, but never succeeded.

function Draw_and_Rotate(){
   for (b = world.GetBodyList() ; b; b = b.GetNext()){
      var angle = ((b.GetAngle()*180)/(Math.PI))/SCALE;
      var angle_vel = ((b.GetAngularVelocity()*180)/(Math.PI))/SCALE;
      var pos = b.GetPosition();
      console.log((angle));
      if (b.GetUserData() == "bo_img"){
         ctx.save();//save the ctx state prior changing it.This method pushes the current state onto the stack.
         ctx.translate(pos.x*SCALE , pos.y*SCALE );
         ctx.rotate(angle);
         ctx.drawImage(box_img, - (box_img.width / 2), - (box_img.height / 2));
         ctx.restore();//restoring ctx state.This method pops the TOP state on the stack, restoring the context to that state.
      }

   }
}

this is the part that deals only with one body and its image. If someone needs some more clarification please ask....


texts: Rotate coordinates back after rotating game context (geometry)

texts:
To achieve something similar to the image below using HTML5 canvas one can simply write the following:

var TO_RADIANS = 0.0174532925;
context.translate(30, 20);
context.rotate(30 * TO_RADIANS);
context.drawImage(img, 0, 0);

My problem comes when I want to convert the coordinates from inside the translated/rotated context back to the main context. For example, if a missile were shot from 0,0 inside the translated/rotated context along the X axis, what formula would you use to then convert its position to the outer context?


texts:
I am trying to load a texture into my 3d graphics application. I am having trouble with my sampler state specifically. There are no errors generated just my little popup window saying, "Texture failed to load". I did a bit of debugging and couldn't find why my sampler is having trouble loading. All of the HRESULTs return S_OK and yet it throws a popup at me.

resourceManager.h

#pragma once

#include "renderer.h"
#include <d3dx11tex.h>

class ResourceManager
{
private:
    ComPtr<ID3D11SamplerState> m_Sampler;
    ComPtr<ID3D11ShaderResourceView> m_Texture;

    Renderer m_Renderer;
public:
    ResourceManager(Renderer& renderer);

    inline ComPtr<ID3D11SamplerState> GetSampler() const { return m_Sampler; }
    inline ComPtr<ID3D11ShaderResourceView> GetTexture() const { return m_Texture; }

    bool CreateTexture(LPCWSTR file_name);
};

resourceManager.cpp

#include "resourceManager.h"

ResourceManager::ResourceManager(Renderer& renderer)
    : m_Renderer(renderer)
{

}

bool ResourceManager::CreateTexture(LPCWSTR file_name)
{
    auto handlerR = D3DX11CreateShaderResourceViewFromFile(m_Renderer.GetDevice().Get(), file_name, nullptr, nullptr, m_Texture.GetAddressOf(), nullptr);
    if (FAILED(handlerR)) return false;

    D3D11_SAMPLER_DESC sampDesc;
    ZeroMemory(&sampDesc, sizeof(sampDesc));
    sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampDesc.MinLOD = 0;
    sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
    auto handlerS = m_Renderer.GetDevice()->CreateSamplerState(&sampDesc, m_Sampler.GetAddressOf());
    if (FAILED(handlerS)) return false;

    return true;
}


texts: What to do to UV coordinates, when swapping Z/Y coordinates (axis) of the geometry?

texts:
In my Maxscript exporter I have the ability to flip the Z/Y axis by simply swapping the Z and Y co-ordinates.

When swapping the axis this way, what is the correct thing to do to the UV coordinates? (e.g. do I need to swap the U or V, or invert one or both?)

Thanks!


texts: In my game I have watch video earn coins system, now I want to program a delay so the user cant watch the video every 5 seconds, for example I want to let him watch every 6 hours, but I'm not sure how can I do that, how can I program a timer that will count down even if the app is closed or how does this kind of timer work, I mean everyone saw this in many games where they count down days or hours until some gift or something. Any help is appreciated.


texts: I want my player to glow like in a loop of on and off for light it emitting and when he touches certain material with different light it should glow with that color


texts: How can I compile a Direct3D 9 effect from a file?

texts:
I started working with shaders recently in DirectX9. I noticed that there is a D3DXCompileShaderFromFile function for IDirect3DVertexShader9 and pixel shader. Which compiles the shader and gives you the compiled code so you can put that into a file and then read it.

But is there a way to do it with the ID3DXEffect or is IDirect3DVertexShader9 the only way?


texts: How can I move an object over linerenderer lines positions?

texts:
I have 4 cubes the first 3 cubes connected with two lines one of the lines is curved. The fourth cube I want to move over the lines. The lines is built using linerenderer and in the linerenderer there are 397 positions. I created a small script that move an object over the positions. I checked and I have in the array 397 positions and the loop get to 397 but the object (Cube (3)) never moving all the positions only some. Or maybe the positions I get are not the same in the linerenderer ?
This screenshot show some of the positions in the linerenderer this is the positions I want the object to move on :

Why the object is not moving over all the positions , only on some ?
And this is the script I created that should move it :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveOnCurvedLine : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public GameObject objectToMove;
    public float speed;

    private Vector3[] positions = new Vector3[397];
    private Vector3[] pos;
    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {
        pos = GetLinePointsInWorldSpace();
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        //Get the positions which are shown in the inspector
        var numberOfPositions = lineRenderer.GetPositions(positions);
        //Iterate through all points, and transform them to world space
        for (var i = 0; i < numberOfPositions; i += 1)
        {
            positions[i] = transform.TransformPoint(positions[i]);
        }

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        if(index <= pos.Length - 1)
        {
            objectToMove.transform.position += pos[index] * Time.deltaTime * speed;
            index++;
        }
    }
}

Now I checked using a breakpoint the first position in the linerender at index 0 is : X = 30.57, Y = -6.467235, Z = 4.98
But in my script in the pos array I see that in index 0 the position is :
X = 30.6, Y = -6.5, Z = 5.0
And the result is that the object that move Cube(3) is moving only some of the way and also it's not exactly on the line :

Why the object is not moving over all the positions , only on some ?
Something is wrong in my script with getting the right positions from the linerenderer and maybe also the loop and the move is wrong. I can't figure out ho to do it.


texts: Is there any way to detect cpu/battery temperature on Android 7.0+ platform in Unity?

texts: I tried WeTest but it's not working because my test device is Android 8.1. Also, I tried Emmagee however it's just working on Android 6.0 and below. Is there any other thing?


texts: How to combine objects in a rendered scene with and without bloom effect?

texts:
I'm working on a game and engine as I go under OpenGL.

I've had a bloom effect in place for a while that works as a post-procesing effect on the entire screen. It's been fine up until now.

I have an object that is made up of a few meshes, and one of these meshes is mostly white. The result is it blooms like crazy, but I really don't want it to.

The only way around it I can see is that the objects I do want to have bloom would need to be rendered to a bloom-framebuffer from which I can bloom (and store the depths) to then mix back in with the rest of my scene.

Is this the only way to go about it? It seems like a lot of work to simply isolate something from a screen-wide affect.


texts: Why might a body suddenly stop while moving on continue platform?

texts:
I have a 32x32 sprite and I make some to be platform like this

for (int i = 0; i < 15; i++) {
    attachChild(new Ground(32 * i, 200, regPlatform, vertexBufferObjectManager, physicsWorld));
}

And I have another sprite (32x32 also) moving over those platforms (A player object)

attachChild(new Player(10, 10, regPlayer, vertexBufferObjectManager, physicsWorld));

And the physicsWorld connects the player like this (Where move=1 when user click right button, and move=2 when user click left button)

physicsWorld.registerPhysicsConnector(new PhysicsConnector(this, body, true, false) {
    if (move == 1) {
        body.setLinearVelocity(new Vector2(8, body.getLinearVelocity().y));
    } else if (move == 2) {
        body.setLinearVelocity(new Vector2(-8, body.getLinearVelocity().y));
    }
}

The Player moves smoothly form left to right and reverse. But sometimes, it is blocked.
If the player move back a bit, and back again where it is blocked, it isn't blocked any more at the same place.

Anyone has any idea to fix this? Maybe it is a bug of andengine and box2d and I need some trick here? Please help me. (The two sprites above are just normal png with 32x32px)

Player image:

Platform image:


texts: Unity Photon Networking - Cant understand OnPhotonSerializeView

texts:
In all tutorials I see that an object sends data over the network and receives the data.

For sync in the same method:

Code:

void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info){
        if (stream.isWriting) {
            stream.SendNext (transform.position);
            stream.SendNext (transform.rotation);
        } else {

            Debug.Log("never gets called ");

            //never gets called...

            transform.position = (Vector3)stream.ReceiveNext ();
            transform.rotation = (Quaternion)stream.ReceiveNext ();

        }
    }

But when I test my code, the lower part, where the data gets received, is never executed!

I never see the logs. But the object is SYNCHED because it is set in the inspector:

But the problem is that the object is not interpolated so it looks kind of funny.

So, I need to know how can I make the upper method to work so I can do some interpolation stuff.


texts: Find the direction a Projectile should be fired from a Moving Object to hit another moving Object?

texts:
I am trying to do a simple AI Controller, which fires Missiles at the surrounding targets in the Scene.

The AI Controller can fire projectiles when moving or stationary.
The Targets are either stationary or move around in the scene with a Constant Velocity and can't fire projectiles.

I did some searching on Stack overflow and came up with this code to find the direction the AI controller must fire the projectile (constant speed) to hit a target travelling at a constant velocity(it can also be stationary):

private bool GetProjectileDirection(GObject target, GObject source, out Vector3 direction)
{
    // Initialize direction to Zero
    direction = Vector3.zero;

    // The Relative Position between the AI Controller and the target.
    Vector2 w = new Vector2(target.Position.x - source.Position.x, target.Position.y - source.Position.y);

    // The Relative Velocity between the source and the target.
    Vector2 v = new Vector2(target.Velocity.x - source.Velocity.x, target.Velocity.y - source.Velocity.y);

    // Quadratic Equation Co-efficients
    float a = Vector2.Dot(v, v) - BULLET_SPEED * BULLET_SPEED;
    float b = Vector2.Dot(w, v);
    float c = Vector2.Dot(w, w);

    float root = (b * b) - (a * c);

    // The Problem seems to occur here as this becomes less than zero most of the time,
    // and exits the function.
    // But on the screen, the object is well within the range for the AI to fire at it
    if (root < 0)
        return false;

    // If root < 0, then this becomes NaN and brings the simulation to a crawl
    double t = (-b - Math.Sqrt(root)) / a;

    double shootX = w.x + t * v.x;
    double shootY = w.y + t * v.y;

    double theta = Math.Atan2(shootY, shootX);
    direction = BULLET_SPEED * new Vector3(Math.Cos(theta), 0, Math.Sin(theta));

    return true;
}

I am pretty sure I am missing something. I just can't pinpoint what exactly is it. As a result, the AI seems to miss most of the targets around it.


texts: Implementing audio for a game made using JMonkey?

texts: Is it possible to implement music/SFX in game made using JMonkey?  If yes, how did you do it?  What did you use?


texts: Single Array Texture, multiple wrap modes

texts:
I have a array texture of which I would like some of its sub-images have wrap modes of GL_REPEAT and others to be GL_CLAMP_TO_EDGE.
From my research, I haven't found a clear answer. It appears Sampler Objects may be what I'm looking for, however I'm unsure as to how to go about implementing this.
As current I have a sampler class which looks like this:
class TextureSampler {
public:
    unsigned int id;

    TextureSampler();
    TextureSampler(unsigned int wrapS, unsigned int wrapT, unsigned int filterMin, unsigned int filterMag);
    ~TextureSampler();

    void bind(unsigned int textureId);
    void unbind(unsigned int textureId);
};

As you can expect the constructor simply sets all the wrap and filter parameters.
I bind with this glBindSampler(textureId, id);. The textureId being that from glGenTextures() and the id from glGenSamplers().
Now when it comes to my implementation, I've created two samplers, one for repeating wrap mode and another for edge clamping. This is where things are a bit murky. I've got two samplers, one texture array... it doesn't seem possible to bind both samplers at the same time and yet how do I access both types in the fragment shader? Google has not been much help and I've read parts of the ARB_sampler_objects extension to see if it had useful information and it seemed to say ...

Should sampler objects be made visible to the shading language.
This is left for a future extension.

I am using GL 4.3, so this is extension is not built-in, however that quote leaves me wondering if I've approached this all wrong. What is the correct approach to this? Is this possible with a single texture array?


texts: How to deal with characters picking up and dropping objects in a 2D game

texts:
I'm quite new to game development, so would like to get a consensus on methods of doing this.

My game features a 2D character that is able to pick up and drop objects, for example, a stick.  My question is: is it advisable / possible to manipulate the image of the character and image of the stick to make it look like the character is now carrying a stick; or is it best to have a separate sprite sheet for the character with the stick and the character without?

EDIT:

To be clear - I have a lot of characters, with a few items (4 separate items and over 20 characters)


texts: Circular Dependencies in an Entity Component System

texts:
I'm developing a top-down shooter in C++ using an entity-component system, and have run into a problem when attempting to refactor powerups. Currently I have a PowerupSystem that is essentially a load of if...else statements that directly modifies player entity attributes (for example speed).

I'd like to move towards using different powerup classes that inherit from a base PowerupComponent class that encapsulate powerup behaviour. An example of this would be SpeedPowerup. These derived classes would have a constructor that changes a value in the player entity, and a destructor that sets it back to its original value.

The problem I'm having is that the powerup constructors and destructors need access to the player entity data to make these changes (stored in my World class), giving me a circular dependency issue.

The dependency is:

world -> powerup system -> powerup -> world

Any ideas on how I could overcome this issue are appreciated.

Thanks in advance,
Rich.


texts: What is the exact unit in LibGDX if it says "private static final float WORLD_SIZE = 480"?

texts:
In the code I see that the WORLD_SIZE variable was initialized with 480
private static final float WORLD_SIZE = 480;

What exactly the 480 means, are they pixels, cm or meters?


texts:
I have a spritesheet:

var spriteSheet = new createjs.SpriteSheet({
    // ...
    frames: { width:520, height:600, regX: 260, regY:300 }
    // ...
});

I am computing it's physics body as follows:

var bounds = entity.sprite.getTransformedBounds();
halfWidth = bounds.width / 2,
halfHeight = bounds.height / 2,
// ... Create the physics body

The result:

The ground is a solid body, and the sprite is dynamic. I would like the sprite's feet to touch the actual ground and get rid of the whitespace around the sprite (above, below and sides).

The problem is that there is whitespace in the spritesheet. Each frame is 520x600 in the sheet. I have lots of frames and I would rather not go through each of them to figure out each one's exact dimensions.

Is this possible? Also I'm new to game dev, it's very fun. Is this what applications like TexturePacker are for?


texts: OpenGL-ES: clearing the alpha of the FrameBufferObject

texts:
This question is a follow-up to Texture artifacts on iPad

How does one "clear the alpha of the render texture frameBufferObject"?  I've searched around here, StackOverflow and various search engines but no luck.  I've tried a few things... for example calling GlClear(GL_COLOR_BUFFER_BIT) at the beginning of my render loop... but it doesn't seem to make a difference.  Any help is appreciated since I'm still new to OpenGL.

Cheers!

p.s.  I read on SO and in Apple's documentation that GlClear should always be called at the beginning of the renderLoop.  Agree?  Disagree?  Here's where I read this: https://stackoverflow.com/questions/2538662/how-does-glclear-improve-performance


texts:
What's my problem:

It says there is a null pointer exception in my desktop launcher class even though I haven't really touched it other than add a title and change the width & height. The weird thing is I haven't touched it and I've called my program before.

Desktop Launcher Code:

    package com.kymedgames.poopman.desktop;

    import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
    import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
    import com.kymedgames.poopman.Game;

    public class DesktopLauncher {
public static void main (String[] arg) {
    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.title = "Poopman Adventures";
        config.width = 800;
        config.height = 600;
    new LwjglApplication(new Game(), config);
}
}

My Application Listener class in my core package is named Game.

What I'm trying to accomplish:

Run my application on desktop. (Which I have done before.)

How I'm trying to accomplish it:

By pressing the run button on Eclipse and not touching my desktop launcher other than add a title, width & height.

What I need help with:

Fix this randomly occurring error.

Am I a noob?

Kind of.


texts: How do you calculate if a line is facing a curve?

texts:
Given the 2 points describing a line segment, and the 3 points describing a quadratic bezier curve, how do you calculate if the line is facing towards or away from the curve?

The line has a fixed length, and is stored in 2D as x1/y1 and x2/y2. The curve is a quadratic bezier curve, and is stored as x1/y1 (control point), x2/y2 (bezier point), x3/y3 (control point).


texts:
I'm wondering if there is a way in spritekit to implement water flowing through a path?

like this water flow

Right now I'm generating the path using UIBezierPath and PaintCode

Any suggestion?

Thanks.


texts: How can I get my Android camera system working more like Google Earth's?

texts:
I'm implementing a touch screen interface whereby the user dragging their finger on the screen will rotate the camera in a sphere around the central point.

My code works well for the horizontal swipe (rotation around the y axis), but only covers a smaller angle from the vertical swipe (rotation around the x axis) instead of the full 360. I used the article - Spherical coordinate system form Wikipedia (http://en.wikipedia.org/wiki/Spherical_coordinate_system), specifically the Cartesian Coordinates section, to do this. I've posted my code below. Can anyone help get this working through the full 360 degrees on both axis? See how Google Earth works when you swipe the globe for what I want.

This must have been done a billion times, but Google searches confuse with the phone built in camera, gps and the like. Thanks!

//Get current position
oldX = getPosition().x;
oldY = getPosition().y;
oldZ = getPosition().z;

//convert to inclination/azimuth
camRadius = Math.sqrt((oldX * oldX) + (oldY * oldY) + (oldZ * oldZ));
inclinationTheta = Math.acos(oldZ / camRadius);
azimuthPhi = Math.atan2(oldY,oldX);

.
.
.

//use touch screen changes (deltaTouchX and Y)
inclinationTheta = (inclinationTheta + deltaTouchScreenX) % (2 * pi);
azimuthPhi = (azimuthPhi + deltaTouchScreenY) % (2 * pi);

//get new co-ordinates
newX = camRadius * Math.sin(inclinationTheta) * Math.cos(azimuthPhi);
newY = camRadius * Math.sin(inclinationTheta) * Math.sin(azimuthPhi);
newZ = camRadius * Math.cos(inclinationTheta);

//set new position
setPosition(newX, newY, newZ);


texts:
I've been working on a deferred decal system. So far I have finished the projection part, meaning I can click something in the scene and it will properly project a decal onto the surface of the object.

There are a couple other things I wish to add to this system: normal clipping and normal mapped decals. Normal clipping is when I discard fragments that are stretched across a sharp angle. Seen here. A way to solve this is to  discard fragments that have a large difference between the normal in the G-Buffer and the decal's normal. This would require reading the G-buffer's normal texture.

In order to do decal normal mapping, I need to blend the decal's normal (from a normal map) with the G-buffer's normal. The requires writing to the G-buffer's normal texture.

I hope it's clear that in order to support these two features, I need to read and write to the normal texture in the same shader pass. Sadly, this is undefined behavior, so I'm wondering if there is some other way to implement these features.


texts: Is there a fully featured OBB class for Ogre3D?

texts:
Is there a fully featured OBB (Oriented Bounding Box) class for Ogre3D?

I don't think there is one by default but I am looking for an alternative which has all the features of the AxisAlignedBox class.


texts: encircling and counting number of objects in a grid

texts:
There is a square grid in which there are empty and filled blocks. A number of contiguous blocks form an object. My bot can find out the status of it's neighbouring 8 blocks (whether they are filled or not). It can move to a neighbouring position if there is no filled block over there.

I have 2 questions

First one :

My code works for the case when there are no tight spaces (i.e., when objects have at least 2 empty blocks between them). But, in the case when there can be a single space between 2 blocks, since my bot has no way of knowing if the neighbouring filled blocks belong to the same or different objects, it fails to encircle the object.

Is there a way to get around this problem?

The other question :

What would be the best search strategy for this? I've been thinking of assigning rewards to neighbouring spaces on the basis of how many unvisited spaces it will allow me to visit if I visit that neigbouring space, but a much simpler strategy seems to be :
keep going right till you hit the wall, the go up and keep going left, then up and right ....
Is there a catch to this approach?


texts: I'm getting a failure returned when calling Direct3DDevice->CreateDepthStencilSurface(). But rather than returning one of the values that the documentation says it should return (D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY), it returns error code 80070057. What does this mean?


texts: What does the TextureRegion.flip() method do?

texts:
I'm learning libgdx and don't understand the purpose of parameters passed to flip(boolean x, boolean y). For example, I have code like this:

texture = new Texture(Gdx.files.internal("data/texture.png"));
textureRegion = new TextureRegion(texture, 0, 0, 20, 20);
textureRegion.flip(false, false);

My TextureRegion is flipped when both parameters are true and not flipped when they are false. But why does it need two parameters when it could have only one? The documentation says nothing about that.


texts:
I've been learning about Procedurally Generated Content lately (in particular, Perlin noise). Perlin noise works great for making things like landscapes, height maps, and stuff like that. But now I am trying to generate structures more like mountain ranges (in 2D, as 3D would be way over my head right now) or underground veins of ores.

I can't manage to manipulate Perlin Noise to do this. Making a cut off point (i.e. using only the tops of the 'mountains' of a heightmap) wouldn't work, because I would get lumps of mountains/veins. Any suggestions?

Thanks,
Numeri


texts:
I have three screens which are at an angle to each other. Basically, the left and right cameras need to move relative to the main camera in such a way that it would look like each screen is a window the player is looking out of (like the cockpit of an airplane).

How can I achieve this effect?


texts: Scale object based on another object's position

texts:
Despite an hour or so of Googling I can't seem to figure out how to calculate the scale factor based on distance. Here's the illustration of my problem.

I've tried manipulating the x values and such, but until now I still cannot figure it out.
Here's the snippet:

Vector3 v3Scale = frontWall.transform.localScale;
frontWall.transform.localScale = new Vector3(v3Pos.x*2.0f , v3Scale.y , v3Scale.z);

Any ideas? Thanks in advance!

UPDATE:

if(getTarget.CompareTag("LeftRightWall") && getTarget.transform.childCount == 1)
        {
            float translate = getTarget.transform.position.x - getTarget.transform.GetChild(0).gameObject.transform.position.x;
            Debug.Log("value :"+translate);
            foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall"))
            {
                Vector3 v3Scale = frontWall.transform.localScale;
                float scaleFactor = translate/frontWall.transform.localScale.x;
                frontWall.transform.localScale = new Vector3(translate , v3Scale.y , v3Scale.z);
            }
            v3Pos.z = getTarget.transform.position.z;
            v3Pos.y = getTarget.transform.position.y;
            getTarget.transform.position = v3Pos;
            getTarget.transform.GetChild(0).gameObject.transform.position = new Vector3(-v3Pos.x, v3Pos.y, v3Pos.z);
        }

The LeftRightWall is the ones that I drag on the picture, with another vertical line as its child. The FrontWall is the horizontal line that is stretched when the LeftRightWall is dragged. Hope its clear enough. Thanks

UPDATE: This is the closest one from what I'm trying to achieve... ((

Here's the code:

float translate = getTarget.transform.position.x - getTarget.transform.GetChild(0).gameObject.transform.position.x;
            Debug.Log("value :"+translate);
            foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall"))
            {
                Vector3 v3Scale = frontWall.transform.localScale;
                frontWall.transform.localScale = new Vector3(translate+v3Pos.x, v3Scale.y , v3Scale.z);
            }

UPDATE:
This is what I'm able to do so far, thanks to the answer below. However I still don't know why the other side of the panel is behaving like that. The scale of horizontal lines also shrinks when I click on the vertical line.

This is the updated code:

ray = mainCamera.ScreenPointToRay(Input.mousePosition);
        float dist;
        plane.Raycast(ray, out dist);
        Vector3 v3Pos = ray.GetPoint(dist);
        if(getTarget.CompareTag("LeftRightWall") && getTarget.transform.childCount == 1)
        {
            float translate = getTarget.transform.localPosition.x - getTarget.transform.GetChild(0).gameObject.transform.position.x;
            Debug.Log("value :"+getTarget.transform.GetChild(0).gameObject.transform.localPosition.x);
            foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall"))
            {
                Vector3 v3Scale = frontWall.transform.localScale;
                float scaleFactor = (translate/v3Scale.x);
                frontWall.transform.localScale = new Vector3(v3Scale.x*scaleFactor, v3Scale.y, v3Scale.z);
            }
            v3Pos.z = getTarget.transform.localPosition.z;
            v3Pos.y = getTarget.transform.localPosition.y;
            getTarget.transform.localPosition = v3Pos;
            getTarget.transform.GetChild(0).gameObject.transform.position = new Vector3(-v3Pos.x, v3Pos.y, v3Pos.z);
        }


texts: How to prevent game client version spoofing

texts:
Basically I have a c++ server that will use a binary protocol to talk to my client (unity game). As part of the login process I want to send the client version to the server. The server then responds saying (assuming login credentials are correct) they are okay to connect, or if the client version is outdated it returns a client version outdated.

My question is, how can I prevent people using old client versions and spoofing as the latest version. As this could potentially lead to server bugs as it is handling an outdated client thinking it is up to date...

Thank you :)


texts: Flip x when direction of the movement changed in Unity

texts:
What is the easiest and the most efficient way to flip x of the SpriteRenderer when direction of the movement changed in Unity?

I use Input.GetAxis() in order to get user input. When it returns 0 I would like to do nothing, when it returns positive number I would like to have x flipped in SpriteRenderer in one side and when number returned is negative another side.

So far I come up with a solution of using a variable which will be keeping the info about to which side the player is turned and flip x if necessary. But I am sure that this is not an efficient way to do it and even not a convenient one since my code will tend to become a lot bigger and messier.


texts: Ball Physics : Smoothing the final bounces as the ball comes to rest

texts:
I've come against another issue in my little bouncing ball game.

My ball is bouncing around fine except for the last moments when it is about to come to rest.  The movement of the ball is smooth for the main part but, towards the end, the ball jerks for a while as it settles on the bottom of the screen.

I can understand why this is happening but I can't seem to smooth it.

I'd be grateful for any advice that can be offered.

My update code is:

public void Update()
    {
        // Apply gravity if we're not already on the ground
        if(Position.Y < GraphicsViewport.Height - Texture.Height)
        {
            Velocity += Physics.Gravity.Force;
        }
        Velocity *= Physics.Air.Resistance;
        Position += Velocity;

        if (Position.X < 0 || Position.X > GraphicsViewport.Width - Texture.Width)
        {
            // We've hit a vertical (side) boundary
            // Apply friction
            Velocity *= Physics.Surfaces.Concrete;

            // Invert velocity
            Velocity.X = -Velocity.X;
            Position.X = Position.X + Velocity.X;
        }

        if (Position.Y < 0 || Position.Y > GraphicsViewport.Height - Texture.Height)
        {
            // We've hit a horizontal boundary
            // Apply friction
            Velocity *= Physics.Surfaces.Grass;

            // Invert Velocity
            Velocity.Y = -Velocity.Y;
            Position.Y = Position.Y + Velocity.Y;
        }
    }

Perhaps I should also point out that Gravity, Resistance Grass and Concrete are all of the type Vector2.


texts: How to add event listener to Gifdecoder in Libgdx?

texts:
I asked this question and implemented the accepted answer. One last piece of the puzzle remains, how to add event listener to the button?

I'm working with a teammate, I suggested to try Gdx.input.justTouched() but he wonders if it's possible to add event listeners like you would do for normal buttons.


texts: Godot: How to get mouse button input for a Tilemap for Cellular Automata

texts:
Conway's Game of Life
I have been working with a tilemap for the implementation of a cellular automata game. My current method for getting mouse button input is using an Area2D as a child of the Tilemap and detecting mouse button input like that.
I have done this and have since been wondering if there is something built in that I can use for this. I have looked into it and cannot find anything better.
Is there something built-in to Node2Ds or Canvas Items that I can use.


texts: How could I simulate projectile collision agaisnt RTS units with primitive colliders?

texts:
For example, humans are easy they are just capsules. But for cavalry, an arrow could hit the horse or the rider. Right now cavalry are also capsule colliders for unit-unit collision, but for projectiles I would need to detect hits on the rider too.
Would a compound collides be the solution? In the Total War series, it looks like arrows have full mesh collision with units. Here is a video showing arrows hitting different parts of the models accurately-- It shows how arrows can hit limbs and the head idk how that is done in such a scale.)
How is this done?


texts: Detect collisions for each instantiated objects

texts:
I want to instantiate cube at a random position when I click mouse and do something (change color or freeze position ..) for each cube when detect collision on the plane.
I tried first few steps:
public Rigidbody cube;

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.name == "Plane")
    {
        //Do somthing for each cube
        cube.constraints = RigidbodyConstraints.FreezePositionY;
    }
}

void Update()
{
    Vector3 position = new Vector3(Random.Range(-5f, 5f), 8,Random.Range(-5, 5));

    if (Input.GetMouseButtonDown(0))
    {
        Rigidbody clone;
        clone = Instantiate(cube,position, Quaternion.identity);
    }
}


texts:
I'm trying to render a model made in Blender. I export it to .fbx and import it in the content pipeline, load and draw it, but it displays like this:

And this is what it looks like in Blender:

Code that draws the model:

foreach (ModelMesh modelMesh in model.Meshes)
{
    foreach (BasicEffect basicEffect in modelMesh.Effects)
    {
        basicEffect.EnableDefaultLighting();
        basicEffect.PreferPerPixelLighting = true;
        basicEffect.World = Matrix.CreateTranslation(Position);
        basicEffect.View = camera.ViewMatrix;
        basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(width / height, MathHelper.PiOver2, 0.1f, 100f);
    }

    modelMesh.Draw();
}

Does anyone know what's wrong with the model?


texts: What kind of hardware would be required to render an Earth sized minecraft like map?

texts:
I have been thinking about this problem. Is it possible with current technology to create a 1:1 replica of the earth in voxel based game? What's the best data structure to store this giant map? Which algorithm should be used to render this data structure in real-time?

These questions make these assumptions:

Each voxel has a resolution of 1 cubic meter.
For simplicity sake,
each voxel requires only 1 byte of metadata information. This information
will be used to store the identify the "type" of the voxel (earth,
water, rock, etc).
The earth volume is 1 * 10ˆ21 cubic meters.
By "current technology" I include anything that is commercially available, but not super computers.
Only the Earth topography and bathymetry will be used to generate the map. Human building, plants or caves are excluded. The underground blocks will be chosen based on geological studies e.g.:  if depth is greater than 3000km render a 'magma' voxel.
Just like in Minecraft, the map is not static, it can be modified in-game.
A 'infinite' draw distance is a big plus, what's the point of having the whole earth in a map if you can't fly up and watch the whole planet?

The first conclusion that I came when I thought about this problem is that storing the Earth data in a linear way is infeasible, assuming that each voxel occupies only 1 byte of memory this would still require 1 zettabyte to store the map. So some kind of compression is required.

I think that a voxel octree could compress the map, but I am not sure by how much. The entropy of this voxel map is probably very low, so I guess that a very high level of compression can be achieved.

Disclaimer

This is a theoretical question, I have no intentions of writing a voxel earth

EDIT

The ESA GOCE has already mapped the Earth geoid with a 1cm-2cm precision. I believe that this information could be used to generate a very precise heightmap of the Earth. This would exclude the need to use an algorithm to fill gaps in the Earth topography.


texts: Assigning components to variables in Unity, benefits?

texts:
I'm wondering if it's beneficial to assign components to variables in Unity C#, as follows

public class SceneLoader : MonoBehaviour
{
    GameStatus gameStatus;

    private void Start()
    {
        gameStatus = FindObjectOfType<GameStatus>();
    }

    public void LoadFirstScene()
    {
        gameStatus.DestroyGame();
    }
}

Whereas the shorter version would be without initialising the object as a variable, besides readability are there benefits to using one way or the other?

public class SceneLoader : MonoBehaviour
{

    public void LoadFirstScene()
    {
        FindObjectOfType<GameStatus>().DestroyGame();
    }

}
```


texts: Unity HDRP Testing - Scene View Issues / Lighting / Shaders / Shadows

texts:
Yo Guys.

Makings this dope, GlassChess Game, Wanted to try out the new HDPR in unity 2018, add the package and volia, its working. (done all settings)

So I used custom glass shader before trying out HDRP.
which is not need now because of the HDRP lit (not the slang word) shader (pretty nice for making glass)

However In my scene viewport it its all funny?

But my Game View (With 1 Camera) is fine?

also as you can see I can't get the glass to work with the chessboard, even without the checkered pattern, the alpha for both are set to 30 out of 255 (30/255)

Unity 2018 (Latest Stable)

please help!


texts: How can I render an OpenGL scene into an ImGui window?

texts:
The picture rapresents what i want to achieve.

I read, somewhere on the Internet, that you can render the fbo and pass that fbo as a texture to render into the ImGui window. The problem is that I don't even know what an FBO is, and how to create it. I just want to have the scene rendered into my ImGui window (just like the scene window in Unity)

How do i do it?


texts:
I have an object that moves towards another object using this line :

transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);

this is it's attributes:

It doesn't use gravity, kinematic and it's Y position is frozen, but it keeps falling to the floor and colliding with it. How do prevent that and keep it floating ?


texts:
I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit.

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

public class UnitController: MonoBehaviour { bool clicked = false; //public float speed = 10f; //public float rotationSpeed = 10f;

 public LayerMask groundLayer;
 public NavMeshAgent playerAgent;
 // Update is called once per frame
 void Update()
 {
     if (Input.GetMouseButton(0))
     {
         Debug.Log("Clicked");
         FindClickPos();
     }
     if (Input.GetMouseButton(1) && clicked == true)
     {
         Debug.Log("I clicked right mouse");
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         if (Physics.Raycast(ray, out hit))
         {
             MoveTo(hit);
         }
     }
 }
 private void FindClickPos()
 {
     RaycastHit hitInfo = new RaycastHit();
     bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
     if (hit == true)
     {
         Debug.Log("I hit " + hitInfo.collider.name);
         if (hitInfo.collider.tag == "TankUnit")
         {
             Debug.Log("I hit" + hitInfo.collider.tag + "!");
             clicked = true;
         }
         else
         {
             Debug.Log("I didnt hit a unit :/");
             clicked = false;
         }
     }
     else
     {
         Debug.Log("I didnt hit anything...");
         clicked = false;
     }
 }
 void MoveTo(RaycastHit hit)
 {
     Debug.Log("Position: " + hit.point);
     playerAgent.SetDestination(hit.point);
 }

}


texts: Why Epic don't release a pre-compiled binary tarball for Linux?

texts: On linux, the 'recommanded' way of installing ue4 on linux is building the engine from github source.  It is very time comsuming.  For each new version, I need serveral hours to rebuild it.  Why don't they just release a pre-compiled tarball so that we can use it right way?


texts:
I want to be able to (only) define game states using Lua script, but I'm not sure how I should do it. Here's what I have in mind currently:

For each state, I will create a .lua file that contains a class (table) that has the same name as the file name. Each table must have a set of event handlers: onEnter (called when the state is entered), onUpdate (called every frame) and onExit (called when exiting the state). So if I want to have a MainMenuState, I will have a file called "MainMenuState.lua" which will contain something like this:

MainMenuState = {}

MainMenuState["onEnter"] = function()
end

MainMenuState["onUpdate"] = function(elapsedTime)
end

MainMenuState["onExit"] = function()
end

Defined states will be exposed to the game engine via a singleton StateManager class. StateManager will have a function that registers a state under a unique name:

void registerState(string stateName, string fileName);

State registration will be done in script by placing the registration codes inside an init script that is called once after the game engine is initialized:

--init.lua
--Register all the states needed by the game
StateManager:registerState("SplashScreen", "SplashScreen.lua")
StateManager:registerState("MainMenuState", "MainMenuState.lua")
StateManager:registerState("InGameState", "InGameState.lua")
-- etc etc

StateManager will also keep track of which state is currently active and also handle state transitions:

//cpp
void changeState(string state);

--lua
StateManager:changeState("PauseMenuState")


texts: Counting triangles and vertices in Unity's cube


texts: Can't access core/assets in a Desktop-Only Libgdx Project

texts:
I'm trying to use libgdx to set up a little quiz application for Desktop.

So I used the setup.jar to create a project and everything went fine (using Eclipse).

The problem is following:

Whenever I try to access the assets in core/assets, as you should do:
Gdx.files.internal(filePath)

I always get a NullPointerException:

java.io.FileNotFoundException: PATH\QuizApplication\desktop\questions.xml (The system cannot find the file specified)

My assets Folder in the desktop project is linked to the core project, and inside Eclipse, I can see the right contents. As you can see from the Exception, the application tries to read the desktop project instead of the core project.

In build.gradle in the desktop project, the link to the core assets folder is there too:

project.ext.assetsDir = new File("../core/assets");

Does anyone know how I might fix this problem, so that I can access the core/assets folder?


texts:
I am trying to make an ImageView change its position based on the direction it is facing.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class Demo extends Application {

    public void start(Stage window) {
        window.setTitle("Changing ImageView position based on angle of rotation");

        int speed = 10; // You can modify the speed here

        ImageView imageView = new ImageView(new Image("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTBJoRKh1UKimWTSLdabW2b8RSLDeSgMfSqqg&usqp=CAU"));
        imageView.setX(100);
        imageView.setY(100);

        imageView.setRotate(65); // This is where you can change the angle of rotation

        Group root = new Group();
        root.getChildren().add(imageView);
        Scene scene = new Scene(root);
        window.setScene(scene);

        final long[] lastNanoTime = {System.nanoTime()};

        new AnimationTimer() {
            @Override
            public void handle(long currentTime) {
                double elapsedTime = (currentTime - lastNanoTime[0]) / 1000000000.0;
                lastNanoTime[0] = currentTime;

                imageView.setX(imageView.getX() + Math.sin(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
                imageView.setY(imageView.getY() + Math.cos(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);

            }
        }.start();

        window.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The above code is based on the code I am using. You can adjust the degrees accordingly to see the issue. The ImageView does not move in the direction it is facing. Note: I found a random .png file online for the purpose of this demo. You can substitute with a different image in you own code in order to better visualize the problem.
The issue is, the ImageView does not move in the direction it is facing. When oriented vertically (0° or 180°) the ImageView moves backward, but when oriented horizontally (90° or 270°) it moves straight ahead like it should. When oriented diagonally, it moves somewhere in between.
What am I doing wrong and how do I fix it?


texts:
Let's say that I have a spritesheet with 4 sprites (standing, breathing player).

When I load it with

player_bitmap = BitmapFactory.decodeResource(resources, R.drawable.player_standing);

it sets it's width and height to for example 100/50 and I have to divide it by 4 and I get four sprites 25x50.

Problem is here that when I switch the app to tablet (I was on phone) sprites have different sizes when loaded.

How to solve issues like this?

Thank you