texts: Trouble drawing repeating and scrolling screen elements from a 2d array for an endless runner in swift

texts:
I've been trying draw level segments for an iOS endless runner using 2d elements that repeat forever. I have a class that generates a random 2d array, then scene elements are drawn and animated to move left based on the 2d array. I also have a random number of ground tiles that generate in between each segment. The problem is when I attempt to have this action repeated forever. Everything I've tried has failed. My question is, what is the most efficient way to achieve this without any spaces in between segments? My goal is to generate the new segment when the end gets close to the viewing area, whereas to not take up unnecissary memory. Here is my code that generates only one segment:

func generateSegment() {

let wholeBlock = SKTexture(imageNamed: "wholeblock")
let halfBlock = SKTexture(imageNamed: "halfblock")
let ySegment = self.frame.height / 9
let randomSpacer = Int(arc4random_uniform(12) + 5)
let startPoint = (ySegment * CGFloat(randomSpacer))
let tempBlock = SKSpriteNode(texture: wholeBlock)
let sizeDifference = ySegment / tempBlock.frame.height
var moveBlock = SKAction.moveByX(-tempBlock.frame.width, y: 0, duration: NSTimeInterval(0.4))
var moveBlockForever = SKAction.repeatActionForever(moveBlock)

// get random 2D Array
var segmentMatrix: [[Int]] = GetLevelSegment().atRandom() as! [[Int]]

//draw random number of ground spaces between segments
for var x = 0; x < randomSpacer; x++ {
    var groundSprite = SKSpriteNode(texture: wholeBlock)
    groundSprite.setScale(sizeDifference)
    groundSprite.zPosition = 98
    groundSprite.anchorPoint = CGPointMake(0,0)
    groundSprite.position = CGPointMake((CGFloat(x) * groundSprite.frame.size.width), 0)
    groundSprite.runAction(moveBlockForever)
    gameLayer.addChild(groundSprite)
}

//set segment start point

//draw a 32 x 9 segment
for var i = 0; i < 9; i++ {
    for var j = 0; j < 32; j++ {
        if segmentMatrix[i][j] == 1 {
            var sprite = SKSpriteNode(texture:wholeBlock)
            sprite.setScale(sizeDifference)
            sprite.zPosition = 98
            sprite.anchorPoint = CGPointMake(0, 0)
            var xPosOne = CGFloat(j) * sprite.frame.size.height
            var xPosTwo = xPosOne + startPoint
            var segFromTop = CGFloat(i + 1) * sprite.frame.size.height
            var yPos = CGFloat(self.frame.height - segFromTop)
            sprite.position = CGPointMake(xPosTwo, yPos)
            sprite.runAction(moveBlockForever)
            gameLayer.addChild(sprite)
        }
        if segmentMatrix[i][j] == 2 {
            var sprite = SKSpriteNode(texture:halfBlock)
            sprite.setScale(sizeDifference)
            sprite.zPosition = 98
            sprite.anchorPoint = CGPointMake(0, 0)
            var xPosOne = CGFloat(j) * sprite.frame.size.height
            var xPosTwo = xPosOne + startPoint
            var segFromTop = CGFloat(i + 1) * sprite.frame.size.height
            var yPos = CGFloat(self.frame.height - segFromTop)
            sprite.position = CGPointMake(xPosTwo, yPos)
            sprite.runAction(moveBlockForever)
            gameLayer.addChild(sprite)
        }
    }
}

}


texts: Make a background Image to fit multiple objects?

texts:
In the Hierarchy, I have a GameObject named "Buttons" to which I added an  Image component.

I would like that the ok sprite to cover (be background of) all the buttons: START GAME, OPTIONS, CREDIT and EXIT.

But the ok sprite is somewhere in the top left corner behind the START GAME button on its left side and is very small.
This happened when I clicked in the Inspector in Image on Set Native Size.

I want to make it big enough to cover all the buttons but I'm not sure how.


texts: How can I draw an arrow at the edge of the screen pointing to an object that is off screen?

texts:
I am wishing to do what is described in this topic:

http://www.allegro.cc/forums/print-thread/283220

I have attempted a variety of the methods mentioned here.

First I tried to use the method described by Carrus85:

  Just take the ratio of the two triangle hypontenuses (doesn't matter which triagle you use for the other, I suggest point 1 and point 2 as the distance you calculate). This will give you the aspect ratio percentage of the triangle in the corner from the larger triangle. Then you simply multiply deltax by that value to get the x-coordinate offset, and deltay by that value to get the y-coordinate offset.

But I could not find a way to calculate how far the object is away from the edge of the screen.

I then tried using ray casting (which I have never done before) suggested by 23yrold3yrold:

  Fire a ray from the center of the screen to the offscreen object. Calculate where on the rectangle the ray intersects. There's your coordinates.

I first calculated the hypotenuse of the triangle formed by the difference in x and y positions of the two points. I used this to create a unit vector along that line. I looped through that vector until either the x coordinate or the y coordinate was off the screen. The two current x and y values then form the x and y of the arrow.

Here is the code for my ray casting method (written in C++ and Allegro 5)

void renderArrows(Object* i)
{
    float x1 = i->getX() + (i->getWidth() / 2);
    float y1 = i->getY() + (i->getHeight() / 2);

    float x2 = screenCentreX;
    float y2 = ScreenCentreY;

    float dx = x2 - x1;
    float dy = y2 - y1;
    float hypotSquared = (dx * dx) + (dy * dy);
    float hypot = sqrt(hypotSquared);

    float unitX = dx / hypot;
    float unitY = dy / hypot;

    float rayX = x2 - view->getViewportX();
    float rayY = y2 - view->getViewportY();
    float arrowX = 0;
    float arrowY = 0;

    bool posFound = false;
    while(posFound == false)
    {
        rayX += unitX;
        rayY += unitY;

        if(rayX <= 0 ||
            rayX >= screenWidth ||
            rayY <= 0 ||
            rayY >= screenHeight)
        {
            arrowX = rayX;
            arrowY = rayY;
            posFound = true;
        }
    }

    al_draw_bitmap(sprite, arrowX - spriteWidth, arrowY - spriteHeight, 0);
}

This was relatively successful. Arrows are displayed in the bottom right section of the screen when objects are located above and left of the screen as if the locations of the where the arrows are drawn have been rotated 180 degrees around the center of the screen.

I assumed this was due to the fact that when I was calculating the hypotenuse of the triangle, it would always be positive regardless of whether or not the difference in x or difference in y is negative.

Thinking about it, ray casting does not seem like a good way of solving the problem (due to the fact that it involves using sqrt() and a large for loop).


texts: Calculating camera zoom value (top-down)

texts:
I need some help in 'camera maths'. I have a birds eye view of two characters. One character is static and the other can move. I would like the camera to always show both characters in full and, in order to simulate 'zooming out', I'm uniform-scaling the objects. The static character is always at the top of the screen and so the 'camera' can't move along the Y-axis (otherwise the static character would not be shown in whole). However, it can move along the X-axis as far as possible, until the screen reaches the side of the static character. How can I calculate the minimum distance the camera should zoom out in order to ensure that both objects are always on screen?

I hope that makes sense, but I'd be happy to try and clarify it if need be. Thanks.


texts: Algorithm for Circle with fixed radius to cover most points

texts:
I'm in need of an algorithm to find the best spot for a circle with a fixed radius r to cover as many points as possible on a 2D grid, preferably O(n).

Currently I tried 2 different approaches:

The averaging Method
The 'Heat-Map' Method

On the averaging Method I calc the center of all points and then I check how many points are in range (r) of that center, if the number is as high as the given points it returns the spot, else the furthest point is removed from the list and the steps repeat.

+: Very fast
-: Often inaccurate

On the Heat-Map method I generate possible circle center points around all points. If a point is already created I increase it's count by 1. The point with the highest count and lowest total distance to the points in range (r) is the center.

+: Perfect center (depending on scale)
-: Slow (depending on scale)

About scale: map is huge 10000x10000, a circle with radius 400 would contain thousands of possible centers, so I scale all points to the same system with roundings.
The higher the scale, the less points and faster algorithm but more inaccurate center. But still more accurate than 1. Method.

Do you guys know any other algorithms/ways/Tipps/Performance Boosters?

Edit: maybe minimum enclosing circle + removing furthest Point Till MEC.radius <= Radius...

Edit2: or connect all points with lines and check for most intersections, just came to my mind

Edit: Here's an image with Algorithm #2

Another Image of Algorithm #2


texts: How do I design my classes so that my Player.cs code can use class-specific abilities from another script?

texts:
Right now, I have a Player.cs class that handles button pushes, movement speed, damage, Update() etc. At the moment, all of the logic for button presses triggering an ability, and the logic surrounding that ability lives in my player.class. I'd like to take that logic and put it into an Abilities.cs class. All I want in my player at most would be:

public override void Update()
{
    if (button.pushed == "berserkKey")
    {
       ability.berserk();
    }
}

... where for example berserk is a stacking buff but none of that logic is in my player class anymore.

For additional context, I plan to implement a Classes.cs class which will hold the info on classes (warrior/archer/etc) which will know exactly what the class and therefor player can use. The code above will likely abstract out even more when that is the case.

The problem is that my Player class already inherits from another class. How do I go about designing my Classes and Abilities classes in a way that my player can use them in the example above?

I'm also open to a completely different way if my initial thought here isn't ideal.


texts: Updating scene graph in multithreaded game

texts:
In a game with a render thread and a game logic thread the game logic thread needs to update the scene graph used by the render thread. I've read about ideas such as a queue of updates.

Can someone describe to a newbie at scene graphs what kind of interface the scene graph exports. Presumably it would be rather complicated. So then how does a queue of updates get implemented in C++ in a way that can handle the complexity of the interface of the scene graph while also being type safe and efficient. Again I'm a newbie at scene graphs and C++.


texts:
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(mousePos);

This will actually make the camera follow the mouse, but it goes crazy, the camera seems to spin in circles rapidly : here is actually a gif of what is happening. https://gyazo.com/952da6c28e644b7b0e6500a597b6804e/preview Could anyone help me figure how how to fix it?


texts:
I managed to create Zoomable planet. When I get closer to it the respective chunks are splitting and every split holds 4 x 16x16 grid (1024 verts). When getting closer the respective chunks split again and so on. AT the end (let's say when Im on ground), there is so much splits, that when looking on horizont its about 120000 vertices, what is way to much and drops fps to around 7-12. Where I really want like 3-4 layers - near detailed, far less detailed, farest coarse.

I can't get my brain around how to fix this. Any advice appreciated.


texts:
I'm fresh new to unity and I only followed several tutorials. Up to now, I always used/tested the games inside of unity and now I would like to use them even on different systems. Hence, I built the game and I will get a folder with several files, e.g.:

"Tutorial.exe"
"UnityCrashHandler64.exe"
"UnityPlayer.dll"
"WinPixEventRuntime.dll"

and the folders "MonoBleedingEdge" and "Tutorial_Data".

I wonder why is the .exe called Tutorial.exe? Because I'm using files from a tutorial? Probably, however, this is not really my question, instead I would like to know how I start the game..  when I run "Tutorial.exe", the terminal opens and I get the following lines there:

Mono path[0] = 'C:/Users/info/Desktop/game_tutorial/Tutorial_Data/Managed'
Mono config path = 'C:/Users/info/Desktop/game_tutorial/MonoBleedingEdge/etc'
PlayerConnection initialized from C:/Users/info/Desktop/game_tutorial/Tutorial_Data (debug = 0)
PlayerConnection initialized network socket : 0.0.0.0 55319
Multi-casting "[IP] 192.xxx.y.zz [Port] 55319 [Flags] 2 [Guid] 2366299205 [EditorId] 3420877675 [Version] 1048832 [Id] WindowsPlayer(DESKTOP-58KOK07) [Debug] 0 [PackageName] WindowsPlayer" to [225.0.0.222:54997]...
Started listening to [0.0.0.0:55319]
PlayerConnection already initialized - listening to [0.0.0.0:55319]
Initialize engine version: 2018.4.13f1 (497f083a43af)
Forcing GfxDevice: Null
GfxDevice: creating device client; threaded=0
NullGfxDevice:
    Version:  NULL 1.0 [1.0]
    Renderer: Null Device
    Vendor:   Unity Technologies
FMOD initialized on nosound output
Begin MonoManager ReloadAssembly
- Completed reload, in  0.132 seconds
UnloadTime: 0.683600 ms
Setting up 2 worker threads for Enlighten.
  Thread -> id: 2bc8 -> priority: 1
  Thread -> id: 2280 -> priority: 1

I would expect being set into the game? The game has no menu or anything else, one should just be spawning in a landscape and walk around. Instead I end up in the console all the time.

What am I doing wrong?

More information: I'm following this tutorial here: https://www.udemy.com/course/virtual-reality-game-development/learn/lecture/7118680#overview
So it is about a virtual reality scenario but afaik the building and so on shouldn't really be different. These are the options I use to build:

I would like to use the htc vive. I use two different systems: The one where I build the game has steam and steamvr installed but no connected hmd. The other one is in another chamber where I play vr and so on.


texts:
I would really like to get the same metallic reflection look as in CSR Racing for my game in the simplest way possible. It doesn't have to be top-notch, but right now my rendering looks horrible and is in need of some serious improvement. Metallic reflection rendering seems pretty complex (for instance looking at this), so I need some advice on what to try.

I realize CSR Racing renders using some type of environment mapping. Can I cheat using spherical env maps, or do I need cube maps? (Nonetheless I will use static images, it's too much work to generate on the fly, and I'll keep each level in the same "tone" so I think it will work well enough.) How should I map my UVs for the env map? Or should I use the normals? If so how to tranform 3D-normals to 2D? What texture transformation to use? I tried to use the camera transformation with the same UVs I'd have used for a diffuse texture (and using glEnable(GL_TEXTURE_GEN_S)), and there was some... result, but I think that's on the wrong track?

Do I need to use specular maps, even for a shiny, clean metallic surface? When I look at what specular maps are used for it seems like they hold information of what is matte and what is shiny. Any tips and tricks highly appreciated!


texts: Rotate player to a specific angle using Rigidbody2D

texts:
First of all, I'm an absolute beginner in unity and coding so please excuse my lack of knowledge and my mistakes. I didn't achieve to fix my issue with others posts.

I'm trying to do a little top-down 2D RPG in which you move your character using the keyboard.

What I have for now:

The player can go in 8 directions,

The player rotation follows the directions smoothly using the rigidbody2D.rotation BUT although it works well for angle from 0° to 180° there is a problem with angle > 180° or < 0°. For example, the character is facing -135°, we want our character to go down which means 180°. Instead of going to -180 which is the same modulo 360° he turns the other way and do almost a full turn for just a 45° angle movement.

I tried another solution by using transform.rotation and quaternions but I also have an issue with that method. While the movements work great, the velocity of the character seems affected by the Quaternion.Slerp because when the Slerp finishes, the character slow down.

The 2 rotation codes I tested (i do not use them simultaneously if you were wondering):

void GetRotation()
    {
        myRigidbody.rotation = Mathf.Lerp((myRigidbody.rotation), angle, angleRotation);
    }

void GetRotation()
    {
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, angleRotation);
    }

My movement code for one direction:

if (// Get Inputs)
    {
        angle = 0f;
        GetRotation();

        myRigidbody.velocity = Vector2.up * speed * Time.deltaTime;
    }

How would you fix that or what could I read to understand what goes wrong ?

Thank you in advance!


texts: Can you trilinear sample a non volume texture?

texts:
Let's say that i have a regular 2d texture (not a volume texture).  Is it possible to do trilinear texture sampling of that texture even though it isn't a volume texture in opengl or directx?

Specifically, if i had a 2x4 texture laid out like below where A through H are pixels:

A B
C D
E F
G H

What I'd like to get is a trilinear sample being the result of linearly interpolating the bilinear sampling of (A,B,C,D) and (E,F,G,H).

I know i could take two bilinear texture samples and lerp them to get what I want, but is there a hardware supported way to do this?


texts: Maya users; how can I create my own particle emitter in Maya?

texts:
(Originally posted in the Programmers Stack Exchange, but was told to ask here instead. Whoops.)

Before you answer this with "well, use the built-in particle emitter", read further.

For one of my university assignments, I have to build a scene involving a Catherine wheel (a spinning firework, basically) attached to a fence post in Maya 2015. I had intended on using Maya's built-in particle emitter, but my lecturer has told me that he would prefer me to create my own.

I have only a vague idea of what to do. I know that I need to assign a position, velocity, lifespan and a trigger flag that re-spawns each particle (all of which are arrays that depend on the number of particles the user wishes to spawn), but I don't know how to arrange them.

Any tips and advice would be appreciated.

Thanks


texts: UnityEditor related classes can not be referenced. Why?

texts:
I have two classes. Both of them are placed in the editor/interface_field folder.
using System;
using UnityEngine;

namespace editor.interface_field
{
    public class RequiredInterfaceAttribute : PropertyAttribute
    {
        public readonly Type type;

        public RequiredInterfaceAttribute(Type type)
        {
            this.type = type;
        }
    }
}

    using UnityEditor;
    using UnityEngine;

    namespace editor.interface_field
    {
        [CustomPropertyDrawer(typeof(RequiredInterfaceAttribute))]
        public class RequireInterfaceDrawer : PropertyDrawer
        {
            public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
            {
                if(property.propertyType == SerializedPropertyType.ObjectReference)
                {
                    var requiredAttribute = this.attribute as RequiredInterfaceAttribute;

                    EditorGUI.BeginProperty(position, label, property);

                    property.objectReferenceValue =
                        EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true);

                    EditorGUI.EndProperty();
                }
                else
                {
                    var previousColor = GUI.color;
                    GUI.color = Color.red;

                    EditorGUI.LabelField(position, label, new GUIContent("Property is not a reference type"));

                    GUI.color = previousColor;
                }
            }
        }
    }

I have another class.
using editor.interface_field;
using UnityEngine;

namespace interface_user.implementations
{
    public interface IInterface {}
    public class InterfaceUser : MonoBehaviour
    {
        [SerializeField]
        [RequiredInterface(typeof(IInterface))]
        UnityEngine.Object interfaceImplementation;
    }
}

The [RequiredInterface(typeof(IInterface))] line throws the following error:

The type or namespace name 'RequiredInterfaceAttribute' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS0246)

I can not understand why does not Unity see the RequiredInterfaceAttribute class and how could I make it see it.


texts: Looking for online resources to understand game camera properties

texts: What are some good online resources to understand game camera properties, such as fov, aspect-ratio and more?


texts: Rotation of rectangles offsets render position

texts:
I have an unknown number "Bricks" that must follow a straight, but not always level, path. Each brick is rotated around one central point properly to form a shape of intersecting paths. My problem arises when rendering an image for a rotated brick. By rotating an image the width and height are changed thus altering the relative render point (top left, x/y). I need to find out what render offset would be necessary to make sure each brick is an equal relative distance from the center rotation point. I am using MonoGame (XNA) if that matters, but I don't currently have any code worth sharing (I need to understand this concept before anything else is worth coding). I hope the following image helps to visualize my problem. The example uses 3 bricks but that won't always be the case.
http://i.stack.imgur.com/rO4IT.png


texts:
Hello I have a top down survival game where you shoot bad guys(green squares). The player can collide with certain tiles and so can the mobs but I want the mobs to go around the tile if there is a path and not juts look in the direction of the player. How could I do this. Here is my mob class, collision class and block class

public class collision {

public static boolean iscolliding(Point p,block b){
    return b.contains(p);

}

}

public class block extends Rectangle {
private static final long serialVersionUID = 1L;

public static int blocksize = 40;
private int id;

private Image i;

public static Rectangle r = new Rectangle(Comp.mx, Comp.my, 1, 1);

public static boolean c = false;

public block(int x, int y, int id) {
    setBounds(x, y, blocksize, blocksize);
    this.id = id;
}

public void render(Graphics g) {
    g.setColor(Color.green);

    if (id == 0) {
        ImageIcon i62 = new ImageIcon("res/tiles/air.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }
    if (id == 1) {
        ImageIcon i62 = new ImageIcon("res/tiles/dirt.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }
    if (id == 2) {
        ImageIcon i62 = new ImageIcon("res/tiles/roots.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }
    if (id == 3) {
        ImageIcon i62 = new ImageIcon("res/tiles/hellgrasses/hellsoil.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }

}

public void setID(int id) {
    this.id = id;
}

public int getID() {
    return id;
}

}

public class blob {

public double x,y;

public boolean dead;

public Rectangle r = new Rectangle((int)x, (int)y,20,20);

public boolean canmove;

public blob (int x, int y){
    this.x = x;
    this.y = y;
}

public void tick(){
    r = new Rectangle((int)x- play.camx, (int)y-play.camy,20,20);

    if(!play.isPaused){
        if(x > play.p.x+ play.camx){
        x-=.2;
        }
        if(x < play.p.x+ play.camx){
        x+=.2;
        }
        if(y > play.p.y+ play.camy){
        y-=.2;
        }
        if(y <  play.p.y+ play.camy){
            y+=.2;
        }

        if(r.intersects(play.p.r)){
            play.p.health-=1;
        }
    }

    if(dead){
        if(new Random().nextInt(100) >= 95){
            play.hp.add(new healthPack((int)x,(int)y));
        }
    }
}

public void render(Graphics g){
    g.setColor(Color.green);
    g.fillRect((int)x - play.camx, (int)y -play.camy, 20, 20);
    g.setColor(Color.red);
    g.drawRect((int)r.x , (int)r.y, 20, 20);
}

}

if you need any other info just leave a comment


texts:
In my game I have a Main class in which i am initializing starling framework by passing Game class like below

myStraling = new Starling(Game , stage);

In the game class I have Instances of Welcome class and InGame class these two classes extends starling.display.Sprite.I have a PhysicsHandling class seperately. Now i want to make instance of PhysicsHandling class  in the InGame class.
The physics handling class does not extend any class because it only does calculations. I have made its some variables public to position starling sprites accordingly.

My question is. Is it the right way to integrate physics in starling Performance wise .I mean is there a better way to do that


texts: Unity Trail Renderer artifacts — flickering & disappearing

texts:
I have a projectile prefab that have 2 trail renderers attached to it. Whenever I instantiate another projectile, every trail renderer seems to flicker. This is similar to the question: Changes to one Unity trail renderer causes all of them to flicker

In addition to that, I have other rendering artifacts as well. Having too many trail renderers seems to cause some of them to not draw. Also, sometimes, they just seem to randomly choose not to draw.

As you can see, the left most projectile doesnt want to draw its trail.

Similarly, adding more projectiles, the front projectiles seems to lose all of its trails.

So thus, the 2 issues I am having is

Flicking trail renderers when another is instantiated.
Trails not rendering randomly.

Unity Version: 5.3.2f1


texts: How would I take a texture and render it to a specific size? The texture I'm rendering has a 1:1 ratio so I want to be able to render the whole image like if the window is wide then put black outlines and the left and right and render the texture in the middle and if the window is taller (I don't see why it would be) then do the same with the texture by rendering lines at the top and bottom and rendering the texture in the middle. Does anyone know how to do this?


texts: How to stop counting point when player dies (Destroy)

texts:
In my game, I'd like to stop counting points when the player's y is -4. When the pink and red balls fall off the Plane the player gets points. But it seems a bit strange to be able to collect points after the player dies.

This is the code for the player:

     if (transform.position.y < -4)
    {
       Destroy(gameObject);
       gameManager.GameOver();
    }

And in the GameManager.cs I have this:

   public bool isGameActive;

   public void UpdateScore(int scoreToAdd)
   {
      score += scoreToAdd;
      scoreText.text = "POENG: " + score;
   }

   public void GameOver()
   {
      isGameActive = false;
      restartButton.gameObject.SetActive(true);
      gameOverText.gameObject.SetActive(true);
   }

And this is the code for adding points when the enemies fall over the edge:

    if (transform.position.y < -4)
    {
       Destroy(gameObject);
       gameManager.UpdateScore(pointValue);
    }

How can I make the game stop counting points when the player dies?


texts: Do sprite animations usually run at the same framerate as the game itself?

texts:
Just getting into game development and wondering about fps. For example, Binding of Isaac can run at 60 fps, but looking at its sprite sheet, the walk animation is only 12 frames. The game animation definitely doesn't look like its running at 60 fps, but I think the collision, movement, etc. systems are?

I'm working on a game I plan on running at 60 fps, is this a good frame rate for a first game, and how do you fit sprite frames into a higher frame rate? I assume if you have a 12 frame/second animation, you can run each sprite frame for 5 in game frames.

I've seen people talk about issues in running a 12 frame cycle in a 30 fps game, because the ratio isn't a whole number, so it doesn't scale. Will this be a problem if someone wants to run the game at a lower frame rate? Or is the frame rate locked and the game slows down if a computer can't run it?

Sorry if I'm asking some obvious questions, I'm pretty new to this.


texts: Most efficient way to achieve the following 2D heat wave background effect?

texts:
In Unity, what would be the most efficient way to achieve the following heat wave background effect

Super Metroid - SNES (skip to 34m 5s for those on mobile)

http://youtu.be/yB317FOcU0Y?t=34m5s

Obviously one way of doing this is by animating the sprite directly, which actually might be the most efficient way in terms of GPU, but is definitely more labor intensive. Could a shader be created to do this?


texts: Creating 3D water on Unity for iOS/Android

texts:
I want to render an ocean where players can change waves’ amplitude in real-time. Initially, I would render rolling waves (see picture). As the amplitude increases, I need to transition the rolling waves into breaking waves (see picture). For now, I am not going to show the shoreline onscreen so I don’t need to render breaking waves interacting with the shoreline; I only need breaking waves on the open ocean.

I’ve tried three different approaches so far and I’ve only had success with rolling waves using approach 1. Breaking waves have been impossible so far with all three approaches.

Approach 1: Mesh deformation

I can create smooth rolling waves using the Sine and Gerstner equations.
Since I can’t use these equations for breaking waves, I tried to implement them by using this free plugin whose output is similar to this paid mesh deformation plugin. But there are 2 problems with this plugin approach:

Problem 1: There is no smooth transition between rolling waves generated by approach 1a and the breaking waves generated by the Deform plugin

Problem 2: The output of the plugin does not look similar to real breaking ocean waves in three different ways:

i. No smooth blending with the ocean surface

ii. A large depression is created below the crest

iii. The entire wave is the same height (rather than with more realistic variations)

I considered using vertex shaders but this approach seems similar to mesh deformation.

Approach 2: Fluid dynamics + metaballs

To render an ocean I will need thousands of particles which will be too expensive in terms of performance (especially for mobile devices).

Approach 3: Using mesh files

I can create breaking waves using some 3D software like in this post but then I can’t modify the ocean in real-time. It will be more like a pre-rendered simulation.

To summarize, I am looking for an approach where I can vary ocean waves’ amplitude for a smooth transition between rolling waves and breaking waves.


texts: I have many buttons in my game. There are different texts on them every time. But some texts are too long and get split up into two different lines. Is there any way I can fix this without resizing the button. How do I limit the button to one line. p.s I do have best fit on and need it.


texts: Circle Collider Vibrates on Edge Collider

texts:
I am making a game (kind of bricks) and using edge collider objects as world bounds collider. I am increasing count of balls on each iteration, after 5 balls, balls start to vibrate when they contact with edge colliders. Vibrating means, they do not bounce directly when they contact with edge collider, they vibrate on x axis for some period while they are moving upwards on y axis.

Ball physics: (friction is 0, bounciness is 1)

Wall physics: (friction is 0, bounciness is 0)

I am not updating transform of ball object, directly set a velocity to balls.

Also i've recorded a video for this behavior: https://www.youtube.com/watch?v=K-bjkXZjXjs&feature=emb_logo

Which point i am missing on this setup? Can you help me to solve this problem?

Best,

Edit:

I have a input listener class, that updates BallThrowHandler.thrown variable, when you put your finger to screen, move and release.

Code that adds velocity to balls (which is running on another object):

using UnityEngine;
using System.Collections;

public class BallContainerBehaviour : MonoBehaviour
{
/// <summary>
/// total speed of the balls
/// </summary>
public float totalSpeed = 5f;

public float timeBetweenBalls = 0.2f;

WaitForSeconds wait;

public float degrees = 0f;

Rigidbody2D childBody;
Vector3 speedVector;

float cosinus;
float sinus;

void Start()
{
    wait = new WaitForSeconds(timeBetweenBalls);
}

void Update()
{
    if(BallThrowHandler.thrown)
    {
        //start throw animation

        startBallMovement();
    }
}

// start ball movement if they thrown
private void startBallMovement()
{
    calculateDegrees();

    //speedUpBalls();

    if(BallThrowHandler.thrown)
    {
        StartCoroutine("speedUpBalls");
    }

    CollectBallHandler.CollectingBallsStarted = false;
    BallThrowHandler.BricksMovedDown = false;
}

private void calculateDegrees()
{
    degrees = Vector3.Angle(Vector3.right, BallThrowHandler.ThrowVector) * Mathf.Deg2Rad;
}

private IEnumerator speedUpBalls()
{
    cosinus = Mathf.Cos(degrees);
    sinus = Mathf.Sin(degrees);

    speedVector = new Vector3(totalSpeed * cosinus, totalSpeed * sinus, 0f);

    foreach (Transform go in transform)
    {
        childBody = go.gameObject.GetComponent<Rigidbody2D>();
        childBody.velocity = speedVector;
        yield return wait;
    }
    BallThrowHandler.thrown = false;
}}

And here is whole code for a ball object: (only bottom collider is trigger, left right and top is not)

using UnityEngine;
using System.Collections;

public class BallEndTurnBehaviour : MonoBehaviour
{
Rigidbody2D body;

public float ballMinY;

public GameObject bricksContainer;

private BrickSpawner brickSpawner;
private BrickTurnOverMover brickTurnOverMover;

private const float EPSILON = 0.01f;

private void Awake()
{
    body = GetComponent<Rigidbody2D>();
}

void Start()
{
    brickSpawner = bricksContainer.GetComponent<BrickSpawner>();
    brickTurnOverMover = bricksContainer.GetComponent<BrickTurnOverMover>();
}

private void Update()
{
    if(System.Math.Abs(body.velocity.x) < EPSILON && System.Math.Abs(body.velocity.y) < EPSILON && CollectBallHandler.CollectingBallsStarted)
    {
        transform.position = Vector3.Lerp(transform.position, CollectBallHandler.CollectingBallsPoint, 0.1f);
    }
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if (!CollectBallHandler.CollectingBallsStarted)
    {
        CollectBallHandler.CollectingBallsStarted = true;
        CollectBallHandler.CollectingBallsPoint = transform.position;
        CollectBallHandler.CollectingBallsPoint.y = ballMinY;
    }
    body.velocity = new Vector3(0, 0, 0);

    Vector3.Lerp(transform.position, CollectBallHandler.CollectingBallsPoint, 1f);

    if(!BallThrowHandler.BricksMovedDown)
    {
        brickTurnOverMover.moveBricks();
        BallThrowHandler.BricksMovedDown = true;
        brickSpawner.spawn();
    }
}
}


texts:
I'm looking to create a 2D "spotlight" effect that allows a spotlight on multiple entities.  I.e., as if several sprites were holding torches.  For a single entity (one spotlight), I use a technique where I overlay a gradient sprite and have the centerpoint chase that entity.  This technique works fine for a single spotlight.  Here's a screenshot to illustrate what I'm talking about:
Single Spotlight - Works

The problem I run into is that this technique does not extend to multiple entities.  If I overlay another spotlight image I run into several problems.  Here's a simulated screenshot:
Multiple Spotlights = Problems

The most obvious problem is the visible corners.  This could be solved by making the spotlight image gigantic to cover the whole level, but that doesn't feel right.  The second and more intractable problem is that I'm effectively multiplying the darkness with this technique.  So each sprite added has the effect of darkening everybody else.  Clearly I'm approaching this problem incorrectly.
Any ideas?

Continuing Efforts
There's been some discussion of blending options in the comments.  Here's my current thinking.  In my single spotlight example above, I use an image file that looks something like this:  (I've replaced the transparency with the color green to make it easier to illustrate)

As discussed above, the problem is that alpha blending this image with another image is not going to produce the desired effect.  Instead it will produce this:

That doesn't strike me as a blending options issue.  The problem, it seems to me, is that that sort of image has the transparency mask and image (a black square) built in, when they should be separated.
So instead of a black image with a cut-out transparency built-in, I ought to be using transparency masks that are utilized at run time against the black square.  When doing that, I still can't use a traditional white and black transparency mask or it'll run into the same problem.  Here's an example, this time the white and black represent white and black:

The solution, it seems, would be to apply a transparency mask that itself utilizes transparency.  Something like this:  (green = transparent)

That way, multiple transparency masks could be alpha blended together and THEN used as a transparency mask against the black square.  Here's an example of two of the transparency masks alpha blended together:

Anyway, that's the approach I'm working on implementing.  I'll post results if this works.  What I don't know (at present) is if I can use a transparency mask that itself has transparency.


texts: wrongly scaled on cocos2dx 3.2 when render to multiple fbo (more > 1 deep)?

texts:
i have bug that only happen when retina flag disabled.

i try draw multiple render texture to achive some multi post effect:
so i have 3 render texture,

fbo 1 for final pos effect
fbo 2 for back buffer w/light
fbo 3 for light mask

i apply this using fbo mechanisms of cocos2dx
 push the fbo1 to screen
push the fbo2 to fbo1
fbo 3 just for sampler texture for render in fbo2 shader

gameplay actor will be drawn on fbo2, after that fbo2 will be rendered to fbo1 ( we can apply some effect here) then fbo1 drawn to screen, then do some gui layering.

the thing is all gp actor drawn into fbo2 , "seems" become scaled down 3 times, so its like the small game screen on left bottom corner, but the light from fbo3 or gui that directly drawn to screen normal positioned and not scaled .

i really dontknow who is scale my fbo2, but i check the matrix its all correct. but seems lot setviewport in rendertexture.h, idont know how its work actualy, so if any one know how viewport work on fbo,

no direct open gl acces for my code except attach shader
if i dont use fbo2 one, ( using fbo1 directly ), the bug doesnt happen
** this doesnt happen on retina true ( scaled 2x ) , this happen on win32 or mac when i disabled retina ,
** tracing draw order correcty
** log  below on command:
onbegin fbo1
onbegin fbo2
onbegin fbo3
( i render some sprite to this fbo first ex: alpha gradient mask)
onend fbo3
( i render gp actor here)
onend fbo2
( render attached fbo2 texture with shader carries sampler of attached texture 3)
onend fbo1
( render attached fbo1 texturee)* may caries some shader
( render gui part )


texts: Intercepting DirectX calls and optimizing the overal performance of games

texts:
I would like to use a DirectX proxy dll to intercept (and possibly optimize) the graphics calls being made by normal PC games. I am going to "screen cast" a game with ffmpeg or something similar and then stream it to a handheld, so a lot of things should be skipped to reach a a reasonable balance of encoding time on the server side, as well as keep it reasonably low-bandwith

adaptive things like:

entire frame skipping
skipping shader phases
reducing texture size
nearing the far view plane (resp. culling more objects than usually)
are on my TODO list. I already checked out a few implementations of DirectX proxies (even the DirectX SDK has one - PIX), but most of them are used for logging and debugging purposes, and not really for runtime hacking and quality degradation.

I was curious what other existing implementations there could eb out there. I guess, I am not the only one who came with the idea of "screwing up" the graphics quality post-factum, in order to increase better overal performance.


texts: I'm building a game for iOS. I'm quite new to OpenGL but what I want is to take a 3D model I have made in Google SketchUp and use it in my 3d game. The problem is I don't know how to proceed. I have built 3d graphics in OpenGL before by specifying the vertices, but the 3D shape I have made is too complex. Is there a way .dae files can be broken down and re-formed as an OpenGL 3D model?


texts:
I'm studying a relatively new mathematics degree called 'discrete mathematics'. This degree intertwines mathematics and computer science such that you can solve most mathematical programming problems (and more) while being able to code them (theoretical CS).

Is this something sought after by game developers? My dream is to work for a game developing company and I want to bring something to the table that nobody else brings. In my case, hopefully exceptional mathematical knowledge. You can look at it this way: If you have a mathematical problem, you'd rather want someone of my caliber than a regular mathematician as it's IT related (again, discrete mathematics). But is it needed?

EDIT: This is NOT a duplicate of the supposed duplicate. I am not your every day mathematician which is why I believe that my question has different roots. I am specifically asking the DIFFERENCE between hiring a regular mathematician and a discrete mathematician.


texts:
How do you set up Unity's UI Layout system so that the chat bubble changes in size automatically based on the length of the text? What's the right use of Layout and Content Size Fitter elements?
How do you turn
into


texts: Checking collision in an array - is there a better way?

texts:
MSDN suggested this, but I'm worried about it slowing down the game when there are a lot of objects to check:

for (int i = 0; i < enemy.Length; i++)
{
   if (enemy[i].isActive)
   {
      BoundingSphere enemySphere =
         new BoundingSphere(enemy[i].position,
         enemy[i].Model.Meshes[0].BoundingSphere.Radius *
         enemy[i].modelBoundingConstant);
      for (int j = 0; j < bulletList.Length; j++)
      {
          if (bulletList[j].isActive)
          {
             BoundingSphere bulletSphere = new BoundingSphere(
                bulletList[j].position,
                bulletModel.Meshes[0].BoundingSphere.Radius);
             if (enemySphere.Intersects(bulletSphere))
             {
                enemy[i].health -= 10;
                bulletList[j].isActive = false;

                break; //no need to check other bullets
             }
          }
       }
   }
}

Nested looping like this just doesn't seem like the most efficient way to check if a bullet connects with an enemy. Is there a better way?


texts: Is it possible to use a string somehow converted to match name of a bool?

texts:
I have a Json file holding data for my LineData type i created.

[Serializable]
public class LineData
{
public string lineID;
public string lineDialog;
public float lineDuration;
public string condition;
}

Note the last one, 'condition', that is what I hope to use to hold a name of a specific bool in my code, so that the line can only be spoken when that bool is true.

Is this a decent way to achieve this? Or is it even possible? I've read about making 'custom markup' on my Json things like (!!) and (->) built in the text to mean stuff in my code, but I don't know where to start with it and cannot find any tutorials (I've only seen it on some Youtube GDC lecture style videos from professional game developers working for companies)

But failing the custom markup thing, if I can somehow use the string of the name of the bool, and use that to check the state of it's corresponding bool in the code, that would be enough for me so far.

Any ideas or help is fantastic and very welcome. Many thanks!!!

(PS. The json looks like this  (Im sure you don't need it, but just in case)):

{ "lineDatas":
[
{
    "lineID": "BEDROOM_DAVE_0001",
    "lineDialog": "Yaawwn, up i get for another fun packed day.",
    "lineDuration": 3,
    "condition": ""
},
{
    "lineID": "BEDROOM_DAVE_0002",
    "lineDialog": "Well I think I need a cigarette before I get to work!",
    "lineDuration": 3,
    "condition1": "notSmokedCig"
}
]
}


texts: What is the best abilities modding system that you encounter in games?

texts:
I'm thinking about designing an abilities system (as in a moba game).

Most important goal is to be able to easily create new abilities in the editor, with a low learning curve (ultimate goal: simple visual constructor, without any programming)

I'm searching for existing production systems, which allow to mod abilities, to analyze their design decisions.

By now, I explored DOTA2 system (tutorial >>) and SC2 system (tutorial >>), because of their success in modding community.

What other good abilities systems do you know, that are worth considering?

Thanks!


texts: How can I abort the closing of a dialog in libgdx?

texts:
Dialog dialog = new Dialog("Warning", skin, "dialog") {
    public void result(Object obj) {
        System.out.println("result "+obj);
        if(obj == true) {
            >> abort the dialog closing ? <<
        }
    }
};
dialog.text("Info?");
dialog.button("Yes", true);
dialog.button("No", false);
dialog.key(Keys.Enter, true);
dialog.show();

how to abort the closing of the dialog?


texts: What is the difference between a level designer and an environment artist?

texts: What are a level designer's roles in the development of a game, what are an environment artist's, and how do they compare? Are they overlapping roles? Does a game development team typically have both roles?


texts: Objects' coordinates and scale adjustment according to different devices resolution and aspect ration in Unity

texts:
E.g I have a bunch of objects which are generated in specific coordinates. Let's say in a range of - 5 to + 5 on X axis. I came app with these numbers because of camera size I have in Unity editor.

What if I run my game on few random devices with different aspect ratios and resolutions? Will unity adjust my game automatically so everything fit perfectly or should I do it manually somehow? And how if I should?


texts: A* in 2D grid with obstacles in between graph nodes

texts:
I am using standard A* (and Jump Point Search) for pathfinding in my 2D game. A map in this game is a simple 2D grid (tile-based). A node (i.e. grid cell) in my map graph can either be blocked or walkable. That works fine so far.

Now I got a new requirement: There can be obstacles in between cells as well, i.e. walls. I thought the easiest way to implement this is to make the cell "behind" a wall an obstacle while searching for a path. However, that does not really work, because if I search for a path from the other side of the wall, then "behind" is also on the other side...

So my question: Is there any "best practice" to implement this, or, if not, what are your ideas?


texts: Transform world space using Kinect FloorClipPlane to move origin to floor while keeping orientation

texts:
The Kinect SDK provides a property SkeletonFrame.FloorClipPlane that describes the orientation of the floor plane relative to the camera. MSDN contains slightly more information in the Coordinate Spaces page for Kinect.

I want to determine a matrix that transforms the camera coordinate space to a 'world space'. In this world space the origin would correspond be a projection of the camera position on the floor, ie straight below the camera.

The X axis is to the sides of the camera, but rotated to be parallel to the floor, compensating for pitch
The Y axis is straight up from the ground to the Kinect, compensating for yaw
The Z axis is straight forward from the camera/origin, but rotated to be parallel to the floor, compensating for tilt

The 2 steps in the transformation would be

Translate from the camera position to the ground
Rotate around the origin while keeping orientation

Unfortunately my linear algebra is rusty and always has been.

Solution update:

I adapted the solution below to create the following method that creates a transformation matrix based on the floor normal and camera height:

Matrix CameraTransform(Vector3 normal, float scalar)
{
    // Note the first three coefficients of the plane equation are the normal
    Vector3 yNew = new Vector3(normal.X, normal.Y, normal.Z);
    Vector3 zNew = new Vector3(0, 1, -normal.Y / normal.Z);
    zNew.Normalize();
    Vector3 xNew = Vector3.Cross(yNew, zNew);

    // assumes column vectors, multiplied on the right
    Matrix rotMatrix = new Matrix(
        xNew.X, yNew.X, zNew.X, 0,
        xNew.Y, yNew.Y, zNew.Y, 0,
        xNew.Z, yNew.Z, zNew.Z, 0,
        0, 0, 0, 1);

    Matrix translationMatrix = Matrix.CreateTranslation(0, scalar, 0);

    return rotMatrix * translationMatrix;
}


texts: Input handling in component based design

texts:
I know this question has been asked several times, but I'm still not sure how to implement input handling in a component based engine.

The component based design I used was based on T=Machine's blog series and on Artemis in which Entities are just ids.

There are three main ideas I have in implementing input handling:

The input component will hold events it's interested. The input system will translate key and mouse events to game events and loop through the entities with the input component and if they are interested in the event an appropriate action will be taken by the input system. This action would be hard coded to the input system.
No input component. You would register entities with specific events to the input system. The input system would then send messages (with the entity id and event type) to other systems so that these can take the appropriate action. Or as in the first case, the actions would be hard-coded to the input system.
Similar to the first method, but instead of hard coding the action to the input system, the component would contain a map of events to functions (i.e. std::map<std::function>) which would be called by the input system. This has the added effect of being able to couple the same event to different actions.

Would you recommend any of the above methods or do you have any suggestions that would help me implement a flexible input handling system? Also, I'm not yet familiar with multi-threading but any suggestions that would make the implementation thread-friendly are also welcome.

Note: One added requirement I'd like the implementation to fulfill is that
I'd be able to pass the same input to many entities, like for example moving a camera entity and the player at the same time.


texts: How to code a multi level isometric map?

texts:
I have already worked with isometric grids in the past, but in my current project I found an issue I am not sure on how to solve. I am trying to produce something similar to what's in the below screen:

What I am having trouble with is how to represent the tiles. With a flat 2d isometric grid all you need is an 2d array (even if you have elevation you can just have a z variable in there to track it and then render based on the z variable plus the z variable of nearby tiles). I am not sure how to proceed with this, however.

My plan was to have the map composed of 4-sided polygons that can be placed anywhere, and have a (x, y, z) position. Rendering is easy enough (start with lowest z tiles, go up to the next level, add any stairs that end on that level, keep repeating until all tiles are rendered).

However, how can I do collision checking? Checking if a point (a player) is inside the polygon is not too difficult, but how can I know whether he can move to another tile?

What would be best:

Have tiles holding a pointer to neighbouring tiles? (Seems like a lot of trouble to code for the editor).
Sort the array by Z-level, then search through the array for tiles that are close enough? (Seems slow)
Something else entirely?


texts:
I decided to use an Octree subdivision in my game. After implementing it, I do some research (a few tests and comparisons) and came up with several questions about.

The main question:
How to test my Octree implementation?
Are there some points that I must note while coding an octree? Is it possible to decide how my code works (good or not enough good) without actual game? Or it would be better if I test the Octree in real situation? Is it right to compare my C++ Octree with Octree implementation for other engines (as example I found C# one for Unity)?


texts: Adding physics to a Blueprint actor in UE4

texts:
I am trying to create a dice in ue4 and be able to read off what value it gives. I've made a mesh in Blender and created a texture, imported them and created a blueprint actor and added the static mesh to it.

When I start the game the dice just floats in the air and isn't affected by gravity. I have tried just using the static mesh and I can get that to be affected by gravity. However, I need to add scripts to the object so I can give it a random rotation and read its value, so I created a blueprint actor. I've looked online for a way to give this actor physics, nut nothing.

Does anyone know how I can add physics to a blueprint actor?

Also if anyone has any info on giving the actor a random rotation and reading the value of the dice that would be great.


texts: LIBGDX - Artifacts when scaling background image

texts:
I've got a problem with libgdx.

First off, im working with libgdx and box2d on a little physics game.

Im using the aproach mentioned in this answer and thereby setting my camera to some smallish numbers and it worked out fine so far.

Now I've ran into following problem.
When drawing my background (1920x1080) I am experiencing artifacts ingame and I am not sure where they are coming from.

I tried linear and nearest Filtering on the Texture with no differing results and I scale the image once via

beachSprite.setScale(camera.viewportWidth/Gdx.graphics.getWidth(), camera.viewportHeight/Gdx.graphics.getHeight());

This is what the background image looks when opening it With a regular image viewer:

And this is what it looks like ingame:

Oddly enough, there seem to appear no artifacts with smaller images, like the player character, or they are just too small to notice.

Thanks in advance for any help.


texts: Most efficient way to get the closest point to a 3d rectangle

texts:
I have a 3D rectangle, with 4 points (x,y,z)
And I have a player, who can be anywere (inside the rectangle, outside, not even in the plane, in the corner...).

I would like to get the closest point in that rectangle, to my player. The most efficient way

I have already a struct who can say the closest point to a line:

public struct ExtLine
{
    public readonly Vector3 A;
    public readonly Vector3 B;
    public readonly Vector3 Delta;
    public bool noGravityBorders;//if I want to return true only if player is in the boundary

    public ExtLine(Vector3 a, Vector3 b, bool _noGravityBorders)
    {
        A = a;
        B = b;
        Delta = b - a;
        noGravityBorders = _noGravityBorders;
    }

    public Vector3 PointAt(double t) => A + (float)t * Delta;
    public double LengthSquared => Delta.sqrMagnitude;
    public double LengthLine => Delta.magnitude;

    public Vector3 ClosestPointTo(Vector3 p)
    {
        //The normalized "distance" from a to your closest point
        double distance = Project(p);

        if (distance < 0)     //Check if P projection is over vectorAB
        {
            if (noGravityBorders)
                return (ExtUtilityFunction.GetNullVector()); //an extention who give me an "null vector", not useful here
            return A;
        }
        else if (distance > 1)
        {
            if (noGravityBorders)
                return (ExtUtilityFunction.GetNullVector());
            return B;
        }
        else
        {
            return A + Delta * (float)distance;
        }
    }

    public double GetLenght()
    {
        return (LengthLine);
    }

    public double Project(Vector3 p) => Vector3.DotProduct(Delta, p - A) / LengthSquared;
}

And a struct who can say the closest point to a plane:

public struct ExtPlane
{
    public Vector3 Point;
    public Vector3 Direction;

    public ExtPlane(Vector3 point, Vector3 direction)
    {
        Point = point;
        Direction = direction;
    }

    public bool IsAbove(Vector3 q) => Vector3.DotProduct(q - Point, Direction) > 0;

    public Vector3 Project(Vector3 randomPointInPlane, Vector3 normalPlane, Vector3 pointToProject)
    {
        Vector3 v = pointToProject - randomPointInPlane;
        Vector3 d = Vector3.Project(v, normalPlane.normalized);
        Vector3 projectedPoint = pointToProject - d;
        return (projectedPoint);
    }
}

How can I manage to find my point ?
Thanks for help !


texts: Split a grid into shapes that can be moved back from 4 directions

texts:
Basically I have 4 grids Left, Right, Top, Bottom. Player can choose each of  them and move all the blocks on that grid to the Middle grid to fulfill it, like tetris from 4 directions:

      |0 0 0|
      |0 0 0|             (0 is empty, 1 is generated block)
      |0 0 1|
       _ _ _         Bottom->Mid  Right->Mid  Top->Mid   Left->Mid
|0 0 0|0 0 0|0 1 0|    |1 0 0|     |1 1 0|     |1 1 1|    |1 1 1|
|0 0 0|0 0 0|0 1 1|    |1 0 0|     |1 1 1|     |1 1 1|    |1 1 1| -> Win! Generate
|1 0 0|0 0 0|0 1 1|    |0 0 0|     |0 1 1|     |0 1 1|    |1 1 1|    another game.
       _ _ _
      |0 0 0|
      |1 0 0|
      |1 0 0|

The point here is to make sure there is at least 1 way for player to combine all 4 grids.

What I've tried so far is generate the right order first (Left->Right->Top....), then generate all the blocks 1 by 1. When a block is generated, i perfomn a check with the generated order (move all the blocks in Left to Mid, then Right then Top...) to see if its still working, the code is similar to this:

// (left->right, top->right->botttom->left, top... it doesn't have to be all 4 directions)
Random the right direction order.

Generate all possible coordinates from all the directions from the path above.
Initialize an empty list to store all chosen coordinates.

While(!(Generate enough x*x block))
{
    Get one coordinate from all possible coordinates

    if (Perform a check with the right order and the chosen list)
        Add it into the chosen list.

}

The problem here is a block can be wrong at this point, but it can become right when another block is generated:

          |0 0 0|                                      |0 0 1|
          |0 0 1|                                      |0 0 1|
          |0 0 1|                                      |0 0 1|
           _ _ _                                        _ _ _
    |0 1 0|0 0 0|0 0 0|                          |0 1 0|0 0 0|0 0 0|
    |1 0 0|0 0 0|0 0 0|                          |1 0 0|0 0 0|0 0 0|
    |1 0 0|0 0 0|0 0 0|                          |1 0 0|0 0 0|0 0 0|
           _ _ _                                        _ _ _
          |0 1 0|                                      |0 1 0|
          |0 1 0|                                      |0 1 0|
          |0 0 0|                                      |0 0 0|
 At this point the logic is wrong          But if I add 1 more block to the
  with Top->Left->Bottom order.               top grid, it'll become right.

There is no way to check if the each block is right or wrong without re-calculate all the generated blocks logic

So i want to ask if there a better way, algorithm to do it.


texts:
so I'm doing my first steps with openGL development on android and I'm kinda stuck at some serious performance issues...

What I'm trying to do is render a whole grid of single colored squares on to the screen and I'm getting framerates of ~7FPS. The squares are 9px in size right now with one pixel border in between, so I get a few thousand of them.
I have a class "Square" and the Renderer iterates over all Squares every frame and calls the draw() method of each (just the iteration is fast enough, with no openGL code the whole thing runs smootlhy at 60FPS). Right now the draw() method looks like this:

// Prepare the square coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                                GLES20.GL_FLOAT, false,
                                vertexStride, vertexBuffer);

// Set color for drawing the square
GLES20.glUniform4fv(mColorHandle, 1, color, 0);

// Draw the square
GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length,
                        GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

So its actually only 3 openGL calls. Everything else (loading shaders, filling buffers, getting appropriate handles, etc.) is done in the Constructor and things like the Program and the handles are also static attributes.
What am I missing here, why is it rendering so slow?
I've also tried loading the buffer data into VBOs, but this is actually slower... Maybe I did something wrong though.

Any help greatly appreciated! :)


texts: Slopes vs. Rectangles: Different Collision Points

texts:
My platformer has both rectangular tiles and right-triangle slopes with rectangular hitboxes. My sprites are also rectangular.

Collision with only rectangular tiles works well. Even if there are multiple rectangular tiles, collision still works pretty well.

Sprites can collide with individual slopes correctly as well, however, they collide at a different point. In order for the character's feet to be walking down the slope instead of hovering over it, the collision point for slopes is the bottom-center point. For rectangles, it is either corner.

The problem is moving from a rectangular tile onto a sloped one. The sprite resolves by the corners first, since it is resting atop a rectangular tile. However, the center point is resting above the slope, and the sprite will not move onto the slope until it is entirely moved off of the rectangular tile.

Here's a diagram:

How can I reliably use two different collision points for different tiles in a way that allows sprites to walk between rectangular and sloped tiles?


texts: How can I set agent's speed on off mesh link? I want it to look like a jump, but now it looks like it was in slow motion.


texts: Organizing movement, collision detection, and collision resolution

texts:
There's many articles on the internet focusing on how to implement movement, collision detection, or collision resolution. What I'm wondering is how to put them together, specifically in what order to perform them.

Should one iterate through all physics objects and do movement, collision detection and resolution for each (approach A), or perform movement for all objects, then detect all collisions, and finally resolve all collisions (approach B), or some combination thereof? Is there an approach that is universally superior? If not, what are the pros and cons for each approach (including ones I haven't listed)?

Approach A:

for (all objects)
    object.move
    object.detect_collisions
    object.resolve_collisions

Approach B:

for (all objects)
    object.move

for (all objects)
    object.detect_collisions

for (all objects)
    object.resolve_collisions


texts: How to create seamless and coherent voxel terrain using simplex noise 2D?

texts:
I'm using the simplex noise 2d plugin for unreal engine 4, which can also be understood by most programmers.
I have already implemented chunk generation and dual-chunk noise elevation.
However, each chunk has a unique heightmap and this results in jagged voxel terrains.
Pseudo code:

//Chunk.cpp
for(int chunkWidth = 0; chunkWidth <= 10; chunkWidth++){
   for(int chunkHeight = 0; chunkHeight <= 10; chunkHeight++){
      noiseX = ((chunkWidth / 10) - 0.5) * Frequency;
      noiseY = ((chunkHeight / 10) - 0.5) * Frequency;
      Elevation = SimplexNoise2D(noiseX, noiseY) * 100;
      ChunkLoc = getActorLocation(self);
      SpawnMeshAtLoc(ChunkLoc.x + chunkWidth, ChunkLoc.y + chunkHeight, Elevation);
   }
}

I have another variable available: chunk2DCoord(2D vector coordinate for each chunk)


texts: How do I wait until the player has reached the gameObject to perform the interaction?

texts:
If the player clicks an object to move the player sprite to the object and interact with it, how do I wait until the player has reached the gameObject to perform the interaction?

I have the interaction hooked up okay, but it is executing as soon as the click occurs. I would like the order instead to be (player clicks on object) (player walks to object) (once player is close enough to object the interaction occurs). But if the player moves away before reaching the object then the interaction is cancelled.

I'm not sure if I should use the object's onTrigger? But my question is if I use onTriggerEnter for the gameObject, and then the player cancels the interaction before reaching it, how do I cancel the ontrigger? Is there a better way? Also, I cannot always use an onTriggerEnter because sometimes it is clicking on an empty tile and I want to wait until the player has reached the tile.

Thanks!


texts: Adding Components (classes) to unordered_map in Entity? (Possible typeid as key issue)

texts:
I've got a little test put together that has a couple simple Components that are supposed to be added to an Entity, but the addComponent function isn't working; I think it's got something to do with typeid/component class inheritance, but I'm not sure. It seems to add a single entry to the map of type Component, but nothing else. Any help is much appreciated, thanks!

#include <iostream>
#include <unordered_map>
#include <typeinfo>

using namespace std;

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

//the base component
class Component {
    public:
    Component() {cout<<"new Component created\n";}
};

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

//a "thing" component
class Thing : public Component {
    public:
    Thing() {cout<<"new Thing created\n";}
};

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

//a "what" component
class What : public Component {
    public:
    What() {cout<<"new What created\n";}
};

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

class Entity {
    public:
    void addComponent(Component* c);
    template <typename T> T* getComponent();
    int componentCount();

    private:
    unordered_map<const type_info *, Component *> components;
};

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

void Entity::addComponent(Component* c) {
    components[&typeid(*c)] = c;
}

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

template <typename T>
T* Entity::getComponent() {
    if(components.count(&typeid(T)) != 0) {
        return static_cast<T*>(components[&typeid(T)]);
    } else {
        return nullptr;
    }
}

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

int Entity::componentCount() {
    return components.size();
}

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

int main(int argc, char* argv[]) {
    Entity e;

    e.addComponent(new What());
    e.addComponent(new Thing());

    cout<<e.componentCount()<<endl;

    return 0;
}


texts: How to move an UIView along a curved CGPath according to user dragging the view

texts:
I'm trying to build a interface that the user can move his finger around the screen an a list of images moves along a path. The idea is that the images center nevers leaves de path.

Most of the things I found was about how to animate using CGPath and not about actually using the path as the track to a user movement.

I need to objects to be tracked on the path even if the user isn't moving his fingers over the path.

For example (image bellow), if the object is at the beginning of the path and the user touches anywhere on the screen and moves his fingers from left to right I need that the object moves from left to right but following the path, that is, going up as it goes to the right towards the path's end.

This is the path I've draw, imagine that I'll have a view (any image) that the user can touch and drag it along the path, there's no need to move the finger exactly over the path. If the user move from left to right the image should move from left to right but going up if need following the path.

This is how I'm creating the path:

   CGPoint endPointUp = CGPointMake(315, 124);
    CGPoint endPointDown = CGPointMake(0, 403);
    CGPoint controlPoint1 = CGPointMake(133, 187);
    CGPoint controlPoint2 = CGPointMake(174, 318);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, endPointUp.x, endPointUp.y);
    CGPathAddCurveToPoint(path, NULL, controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, endPointDown.x, endPointDown.y);

Any idead how can I achieve this?


texts: Hide individual regions on a territory map

texts:
I have a map of adjacent irregularly-shaped territories. It happens to be a county map, but that's not important. In the game, the player only sees a few to start, and as he progresses to new territories, the ones adjacent to it are revealed. It's a territory-scale fog-of-war.

I'm using Unity3D, and my inclination is to make a set of planes, each of which has an image of a single territory on it, and then arrange them manually like a jigsaw puzzle. It then is fairly easy to respond to a click on each region and also to mark the planes as visible or invisible, or even do clever things like fade or zoom on individual regions.

This sounds like an arduous task, and if we need to change the visual design of the territories, we'd have to cut up the main map all over again into each of the individual pieces.

Does anyone have a more elegant solution to this problem?


texts: Bullet Physics: Difference between Motion State and World Transform

texts:
In Bullet Physics, when I create a new btRigidBody, one of the parameters passed to the constructor is the btMotionState, which defines the initial pose of the body. However, if I then later want to change the pose of the body manually (for example, if it is a kinematic body), how can I do this?

What I have tried so far, is to use the body's setWorldTransform() function. For example:

glm::mat4 pose;
pose[3][0] = 0.5;
pose[3][1] = 2.0;
pose[3][2] = 1.0;
btTransform new_transform;
new_transform.setFromOpenGLMatrix((float*)&pose[0]);
my_body->setWorldTransform(new_transform);

However, when I then try to read the pose of the object again:

btTransform trans = my_body->getWorldTransform();
std::cout << "Y = " << trans.getOrigin().getY() << std::endl;

It returns the value set in the body's constructor, not the value set in setWorldTransform().

Please can somebody explain the different between the motion state, and the world transform, and how I should go about manually updating the pose of a kinematic object?


texts: Vertex position problem for connected lines

texts:
I’m trying to generate a mesh to display connected segments representing street lines in a mini map. I have problem with vertex orientation that my math knowledge has hard time to resolve.

Let’s consider 3 points p0, p1 and p2.

I use this code to create the vertices from the segment between p0 and p1 (the same code is then used for the segment from p1 to p2):

height = 2.0f; // desired line thickness
vertices[0] = new Vector3(p0.position.x, p0.position.y - height / 2.0f, 0);
vertices[1] = new Vector3(p1.position.x, p1.position.y - height / 2.0f, 0);
vertices[2] = new Vector3(p0.position.x, p0.position.y + height / 2.0f, 0);
vertices[3] = new Vector3(p1.position.x, p1.position.y + height / 2.0f, 0);

The result looks like this:

Not that bad, except that the "thickness" of the line is not constant. If you look closely to the segment left and right borders, they are aligned (going from bottom to top). The problem comes from the “height” variable that is added or subtracted too naively to the positions.

What I’d like to have is something like this, with oriented borders / vertex.

However I don’t know how to proceed.

Any help or comment would be appreciated.
Thanks for your time.

**** EDIT ****
Thanks to @wondra's solution I managed to do what I needed to. Here is how:

    // Returns point of intersection
    // TODO: check if lines are parallel
    public Vector3 LineIntersection(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
    {
        float ma = (p2.y - p1.y) / (p2.x - p1.x);
        float mb = (p4.y - p3.y) / (p4.x - p3.x);

        float ba = p1.y - (p1.x * ma);
        float bb = p3.y - (p3.x * mb);

        float x = -(ba - bb) / (ma - mb);
        float y = ma * x + ba;

        return new Vector3(x, y);
    }

/// --- LOOPING THROUGH POINTS ---

    // @wondra's solution
    Vector2 dir = (sec_node.position - prim_node.position).normalized;
    Vector2 perp = new Vector2(dir.y, -dir.x);

    vertices[vert_idx]      = prim_node.position + (perp * -height / 2.0f);
    vertices[vert_idx + 1]  = sec_node.position + (perp * -height / 2.0f);
    vertices[vert_idx + 2]  = prim_node.position + (perp * height / 2.0f);
    vertices[vert_idx + 3]  = sec_node.position + (perp * height / 2.0f);

    if ( vert_idx > 4 )
    {
        int vert_idx_bis = vert_idx - 4;
        vertices[vert_idx] = LineIntersection(vertices[vert_idx], vertices[vert_idx + 1], vertices[vert_idx_bis + 1], vertices[vert_idx_bis]);
        vertices[vert_idx_bis + 1] = vertices[vert_idx];

        vertices[vert_idx + 2] = LineIntersection(vertices[vert_idx + 2], vertices[vert_idx + 3], vertices[vert_idx_bis + 3], vertices[vert_idx_bis + 2]);
        vertices[vert_idx_bis + 3] = vertices[vert_idx + 2];
    }
/// --- END LOOP


texts: 2D engine design/architecture: transformations

texts:
Hello! I'm working on this hobby little 2D engine in JavaScript because I want to learn how all this things are implemented and architectured in general. Internet is full of resources but most things are mathematical or theoretical stuff, there is very little about implementation or architecture for small 2D engines like the one I'm working in. So, this is my context and at the end are some questions I hope you can help me with:

I have a Body object that has different properties like (pseudo-code):

Body {
    angle: float
    scale: float
    acceleration: 2d vector
    velocity: 2d vector
    position: 2d vector
    update: function()
}

A Body object also has a Model object, which has (pseudo-code):

Model {
    points: Array of [x, y] points
    fillColor: string (hex)
    transform: function(rotate, scale, translate)
}

The transform function receives Angle, Scale and Translate, and returns a new transformed instance of the model.

On every frame I will update the Body object to represent the current state: adding accelerator vector to velocity, velocity to location (and some similar stuff to update the angle and scale if required):

Body {
    update() {
        this.velocity.add(this.acceleration)
        this.location.add(this.velocity)
        this.acceleration.reset()
    }
}

Once the Body object is updated I must do a world-transform of the model so that I can start doing physics related stuff (like collision detection/resolving, interaction forces between bodies, etc).
After that I will do a view-transform, to transform the world-objects into the "perspective" of some other object.

At the moment this is my solution is based in keeing three instances of the Model object withing the Body object, like this:

Body {
    model: the original *Model* with no transformations
    model_world: result of *Model.transform(body.angle, body.scale, body.location)*
    model_view: the result of transforming **model_world** instance with viewport properties
}

Questions:

Do you think there is a better way to handle model transformations? Like maybe one the do not require the Body object to mantain the three instances of the three transformations itself, perhaps.
Can you please give me some suggestions on how to better organize this functionality for a simple 2D engine?

Thank you very much in advance!


texts: OnMouse Events stop working when multiple cameras are active

texts:
I'm working on 2019.4.9f1 on a 2D project using Universal Rendering Pipeline. The camera settings changed so I'm stating it.
I wrote a OnMouseEnter and OnMouseExit in a script to manage whenever my mouse cursor is on top of a SpriteRenderer with a collider located at 0,0,0. I have a main camera located at 0,0,-10. I've tested the script that manages the OnMouse events. It works fine.
Problem: But the moment I add a new camera (UI Camera set to Overlay located at 0,0,-10) in and it is enabled, OnMouse events aren't getting called. Disabling the UI camera makes the OnMouse events work normally.
Solutions that have failed:

I've tried setting the tag of the UI Camera to MainCamera and set
Main Camera's tag to Default.
https://answers.unity.com/questions/241334/onmousedown-w-multiple-cameras-doesnt-work-right.html
I tried making the UI Camera a bit closer to the sprites.
https://answers.unity.com/questions/425478/onmousedown-not-firing.html

I intend to avoid Raycasting and get the OnMouse Events to work because I want to fix the problem and not work around it.
Question: Any possible reason why my OnMouse events aren't called?


texts:
Thats my problem on the Picture...The stripes

How can i fix that?

My Code:

import pygame, sys
from pygame.locals import *

pygame.init()

sound = pygame.mixer.Sound('start.wav')
sound.play()

size = width, height = 1600, 848
speed = [2, 2]
black = (0, 0, 0)

pygame.mouse.set_cursor(*pygame.cursors.broken_x)

screen = pygame.display.set_mode(size)
background = pygame.image.load("background.PNG")
dragon1 = pygame.image.load("dragon1.gif")
screen.blit(background, (0,0))

x,y=0,0
clock=pygame.time.Clock()
speed=250
movex, movey=0,0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    if event.type==KEYDOWN:
            if event.key==K_a:
                movex=-1
            elif event.key==K_d:
                movex=+1
            elif event.key==K_w:
                movey=-1
            elif event.key==K_s:
                movey=+1
    if event.type==KEYUP:
            if event.key==K_a:
                movex=0
            elif event.key==K_d:
                movex=0
            elif event.key==K_w:
                movey=0
            elif event.key==K_s:
                movey=0
    x+=movex
    y+=movey

screen.blit(dragon1, (x,y))
pygame.display.flip()


texts:
I want to make infinite 2D terrain based on my algorithm.Then I want to move it along Y axis (to the left)
This is how I did it :

public class Terrain {
Queue<Integer> _bottom;

Paint _paint;

Bitmap _texture;

Point _screen;

int _numberOfColumns = 100;
int _columnWidth = 20;

public Terrain(int screenWidth, int screenHeight, Bitmap texture)
{
    _bottom = new LinkedList<Integer>();

    _screen = new Point(screenWidth, screenHeight);

    _numberOfColumns = screenWidth / 6;
    _columnWidth = screenWidth / _numberOfColumns;

    for(int i=0;i<=_numberOfColumns;i++)
    {
        // Generate terrain point and put it into _bottom queue
    }

    _paint = new Paint();
    _paint.setStyle(Paint.Style.FILL);
    _paint.setShader(new BitmapShader(texture, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
}

public void update()
{
    _bottom.remove();
    // Algorithm calculates next point
    _bottom.add(nextPoint);
}

public void draw(Canvas canvas)
{
    Iterator<Integer> i = _bottom.iterator();
    int counter = 0;
    Path path = new Path();
    path.moveTo(0, _screen.y);
    while (i.hasNext())
    {
        path.lineTo(counter, _screen.y-i.next());
        counter += _columnWidth;
    }
    path.lineTo(_screen.x, _screen.y);
    path.lineTo(0, _screen.y);
    canvas.drawPath(path2, _paint);
}

}

The problem is that the game is too 'fast', so I tried with pausing thread
with

Thread.sleep(50);

in run() method of my game thread but then it looks too torn.

Well, is there any way to slow down drawing of my terrain ?


texts: How can I consistently map mouse movements to camera rotation?

texts:
I am writing a OpenGL game engine and also an editor for the engine. In my editor, I can import 3D models from FBX/Collada as a scene graph. Now I want to implement the option for the user to rotate and the camera in the viewport using mouse.

I found many links to rotate the camera by some angle based on the delta x and delta y of the mouse. This is fine. But my problem is selecting the axis for rotation.

For example, if the user moves the mouse in the x axis, I am changing the camera's local rotation angle along y axis (the up axis). But this is not always working. In case if the camera node's parent node is rotated 90 degree in the x axis, when I change the camera's local y axis rotation angle, the scene is rotating in wrong direction. So in this case I have to rotate the camera's z axis angle.

This is my problem. So how can I ensure the camera always finally rotate left and right (whatever the parent nodes' angles are rotated) when the user moves the mouse horizontally?

Also I want to mention that when the user moves mouse up and down, I want the camera to rotate up and down always.


texts: DirectX sampling a Texture2DArray interpolates between textures unintentionally

texts:
I'm trying to texture my procedurally generated terrain. Previously I used an array of textures e.g. Texture tex[8], however in the shader you can't access this by index unless you chain if statements (ew), so I switched to using a Texture2DArray where instead you use a 3D UV where the Z component is the texture index. I use texassemble to generate a DDS file containing the Texture2DArray so it can be loaded in with ease.
For whatever reason, DirectX(11) seems to interpolate the Z component whenever the Z changes, resulting in seeing a slice of other textures in the array. I should add I'm trying to change the texture on the same piece of geometry. But I need to do this due to having multiple procedurally generated biomes.

I sample the texture in the pixel shader like so
float4 texCol = Tex.Sample(Sampler, v.UV);

My sampler is set up like this
CD3D11_SAMPLER_DESC samplerDesc(D3D11_FILTER_ANISOTROPIC,
    D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_CLAMP,
    0.f, maxAnisotropy, D3D11_COMPARISON_NEVER, border, 0.f, FLT_MAX);

The unwanted interpolation in question


texts: SharpDX(DirectX 11) N-tier layering of images

texts:
I have an project I'm looking for a better solution to. I have a need to render n images over each other the previous one. So I have loop if you will. This should simulate alpha bending via basic combining the target and overlay pixel color values. Please see code below.

public void Render()
    {
        Device3DModule.DeviceContext.ClearRenderTargetView(Device3DModule.RenderTargetView, Colors.Blue.ToDXColor());

        CompositeShader.Apply();

        foreach (var image in Images)
        {
            Texture2D target = null;
            var pass01 = true;

            foreach (var imageChannel in image)
            {
                if(!imageChannel.IsVisible || imageChannel.Image == null) continue;

                imageChannel.Pass01 = pass01;

                Device3DModule.DeviceContext.PixelShader.SetShaderResource(1, imageChannel.Image);
                imageChannel.CopyToDeviceBuffer(ref m_ChannelSettingBuffer);

                QuadMesh.Draw();

                target?.Dispose();

                target = new Texture2D(Device3DModule.Device, Device3DModule.RenderTarget.Description);
                Device3DModule.DeviceContext.CopyResource(Device3DModule.RenderTarget, target);

                ShaderResourceView = new ShaderResourceView(Device3DModule.Device, target);
                Device3DModule.DeviceContext.PixelShader.SetShaderResource(0, ShaderResourceView);

                pass01 = false;
            }

            target?.Dispose();
            ShaderResourceView.Dispose();
        }
    }

Does anyone have a better idea?


texts: Rotating image angle, direction of object that is resting on floor object

texts:
I have an object, in this case a space ship, resting on a floor or platform object. The bottom of the space ship is flat, and is resting flush with the flat surface of the platform object (due to my collision detection). Now obviously, the player is able to move the space ship by pressing up. The player is also able to turn the ship (image_angle and direction) by pressing left or right, which transfers the speed to that direction if they are flying. However, in the scenario mentioned above where the ship is currently resting flat on a flat surface, if the player presses left or right, the ship still rotates and the sides clip into the surface of the platform, which causes collision detection to essentially glue the ship to the platform. How can I use collision detection to allow the player to still rotate the ship while it is resting on a flat surface, but instead of clipping, have the object perhaps "roll" or fall over?

here is my collision detection:

// Gravity
if (vspeed < 10) vspeed += .02;

// Collision detection
if (place_meeting(x, y + vspeed, obj_block))
{
    while (!place_meeting(x, y+1, obj_block))
    {
        y += 1;
    }
    vspeed = 0;
    hspeed = 0;
}


texts: Make objects slide across the screen in random positions

texts:
I want to make an object appear randomly at the right hand side of the screen and then slide across the screen and disapear at the left hand side. I am working with libgdx. I have this bit of code but it makes items fall from the top down. Please help.

public EntityManager(int amount, OrthoCamera camera) {
    player = new Player(new Vector2(15, 230), new Vector2(0, 0), this, camera);
    for (int i = 0; i < amount; i++) {
        float x = MathUtils.random(0, MainGame.HEIGHT - TextureManager.ENEMY.getHeight());
        float y = MathUtils.random(MainGame.WIDTH, MainGame.WIDTH * 10);
        float speed = MathUtils.random(2, 10);
        addEntity(new Enemy(new Vector2(x, y), new Vector2(-0, -speed)));
    }


texts: How to set up flatbuffers in Android Studio - Gradle?

texts:
Just switching over from Eclipse to Android Studio. I think I'm supposed to use Gradle to automatically download dependencies from the web. Sounds great, but I can't get it working with anything, in particular Google's flatbuffers.

So I found the link on the Maven repository, and I think I'm supposed to do something with the following:

// https://mvnrepository.com/artifact/com.github.davidmoten/flatbuffers-java
compile group: 'com.github.davidmoten', name: 'flatbuffers-java', version: '1.3.0.1'

But the comments in my project's Gradle (which is supposed to be a library by the way - but that's another story...) says I should not place my "dependencies here" (see below)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

So what am I supposed to do? I've heard of "modules" - so I could load flatbuffers in as a module?


texts: How can I combine chasing and obstacle-avoidance in a steering-based AI?

texts:
I'm developing a top-down game in XNA with enemies that wander until they are within range of a player, at which point they begin chasing the player. This works, but I also want them to avoid obstacles around the map while chasing.

I can find tutorials on programming the avoidance behavior, but I'm unsure as how to integrate that into my current AI so that the enemy both chases the players while also avoiding obstacles. I cannot use a pathfinding algorithm like A* because my current AI is steering-based.

How should I go about integrating this?


texts:
I have been thinking about the use of Unity's coroutines recently, and while I've used them in the past, and am already aware of their bad reputation (although I've also seen posts on the unity forums of people who seem to absolutely swear by them), the more I think about it, I'm kind of struggling to see any compelling reasons to use them at all instead of simply creating a new component and simply performing the logic of the coroutine in said new component's Update method. By using a IEnumerator coroutine inside of another component, it seems to me like all it accomplishes is decreasing the cohesiveness of individual components and the re-usability of the component using them.

Is there any convincing argument to actually use coroutines in Unity and would I be missing out by simply not using them? Are there any scenarios I'm overlooking where their use would either be required or prove incredibly useful?


texts: Unity - Trying to copy the render texture for the scene rendered by a camera but it is blank?

texts:
I'm trying to copy the scene rendered by a particular camera to a render target.  I know this should be possible to do without using the camera's target texture as I read through this official Unity article about Command Buffers which avoids any use of them.

Instead, I found that they use the following code in the renderer for blurry refractions (CommandBufferBlurRefraction.cs) to copy the scene to a render target.

    buf = new CommandBuffer();
    buf.name = "Grab screen and blur";
    m_Cameras[cam] = buf;

    // copy screen into temporary RT
    int screenCopyID = Shader.PropertyToID("_ScreenCopyTexture");
    buf.GetTemporaryRT(screenCopyID, -1, -1, 0, FilterMode.Bilinear);
    buf.Blit(BuiltinRenderTextureType.CurrentActive, screenCopyID);

The problem is that I can't get this to work for myself using a very simple scenario of:

Camera renders the entire scene which is a single hexagonal sprite
The command buffer assigned to the camera grabs the BuiltinRenderTextureType.CurrentActive (Scene Render Target)
The command buffer then copies that to another render target
That render target is then drawn in the upper left of the screen on a yellow background

This results in the scene render target being completely blank and not including the white hexagon.

The code I am using is

Camera cameraUsedToRender;
CommandBuffer commandBuffer;
RenderTexture debugRT;
Texture2D debugRTBackground;

void Awake()
{
    // Create debug texture to render
    debugRTBackground = new Texture2D(2, 2);
    debugRTBackground.SetPixels(new Color[4] { Color.yellow, Color.yellow, Color.yellow, Color.yellow });
    debugRTBackground.Apply();

    cameraUsedToRender = Camera.main;
    cameraUsedToRender.orthographicSize = 10f;

    // Create debug render texture to render to using our camera
    debugRT = new RenderTexture(cameraUsedToRender.pixelWidth, cameraUsedToRender.pixelHeight, 16);
    debugRT.Create();

    // Create command buffer
    commandBuffer = new CommandBuffer();
    commandBuffer.name = "Debug";

    // Add the camera buffer to the main camera
    cameraUsedToRender.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, commandBuffer);
}

void OnRenderObject()
{
    // Clear the command buffer
    commandBuffer.Clear();

    // Set the render target
    commandBuffer.SetRenderTarget(debugRT);

    // Clear the render target
    commandBuffer.ClearRenderTarget(true, true, Color.blue);

    // Copy scene into a render target
    // RenderTarget.active = SceneView RT (UnityEngine.RenderTexture)
    commandBuffer.Blit(BuiltinRenderTextureType.CurrentActive, debugRT);

    // Release the render target
    commandBuffer.SetRenderTarget(null as RenderTexture);
}

void OnGUI()
{
    // Draw the debug render target (which should have the SceneView RT copied to it)
    GUI.DrawTexture(new Rect(0, 0, 130, 130), debugRTBackground);
    GUI.DrawTexture(new Rect(1, 1, 128, 128), debugRT);
}

The complete small, simple project that demonstrates this issue can be found here.

Does anyone have an idea how to resolve this as I'm finding the Unity rendering pipeline to be rather confusing at this point?


texts: Can't read .cso files but I can read their .hlsl versions?

texts:
Well I've been trying to read a .cso file to use as a shader for a DirectX program I'm currently making.

Problem is no matter how I implemented a way to read the file it never worked. And after fidgeting around I discover that it's only the .cso files I can't read.

I can read anything else (which means it works) even their .hlsl files. Which is strange because the .hlsl (high level shader language) files are supposed to turn into .cso (compiled shader object) files.

What I'm currently doing is:

vector<byte> Read(string File){
    vector<byte> Text;
    fstream file(File, ios::in | ios::ate | ios::binary);

    if(file.is_open()){
        Text.resize(file.tellg());
        file.seekg(0 , ios::beg);
        file.read(reinterpret_cast<char*>(&Text[0]), Text.size());
        file.close();
    }

    return Text;
};

If I then implement it.

Read("VertexShader.hlsl"); //Works
Read("VertexShader.cso"); //Doesn't Works?!?!

And I need the .cso version of the shader to draw my sexy triangles. Without it my life and application will never continue and I have no idea what could be wrong.

(I've also asked this at stack overflow but still no answers.)


texts: Stop displaying a camera sign in a Scene view in Unity

texts:
How can I stop displaying a camera sign in a Scene view in Unity?

I mean that white thing you see below:


texts: How can I repeat only a portion of an image in Javascript?

texts:
So I'm trying to repeat a portion of my spritesheet as a background. So far, I have attempted this:

var canvas = $("#board")[0],
    ctx = canvas.getContext("2d"),
    sprite = new Image();
    sprite.src = "spritesheet.png";
sprite.onload = function(){
    ctx.fillStyle = ctx.createPattern(spriteBg, "repeat");
    ctx.fillRect(0, 25, 500, 500);
}

As you can see, it repeat the whole image, not just a part of it, and I just can't figure out how to do that last part.


texts: How to stop switching between paths to a moving target?

texts:
I've noticed after implementing A* pathfinding into my game, that there is exploitable/unrealistic behavior that goes on when the player moves between two nodes that alter the path of the AI trying to reach them. I have made a few images to demonstrate this problem.

This image above shows how the pathfinding in my game would behave if the player stood on the opposite side of a wall than my AI. If the player doesn't move it will take this single path to reach them. Assume that the red icon is the AI (enemy) and the blue icon is the target (player).

Now, if the player in this image above moves along the white arrows up and down, and the AI is constantly finding the optimal path to the player (ignore the performance costs of doing that), then the AI will also get stuck moving up and down because the optimal path will constantly shift between going above the wall and going under the wall. Is there a way to modify a standard A* implementation to remedy this? I will include my pathfinding code for clarity, but it's pretty much a standard top down implementation. The "Node" object is a node on my grid, and the grid is an object that holds a list of nodes, with a few functions to find a node from a world point.

public class Pathfinding : MonoBehaviour
{

public Transform seeker, target;
AstarGrid grid;

void Awake()
{
    grid = GetComponent<AstarGrid>();
}

public List<Node> FindPath(Vector3 startPos, Vector3 targetPos)
{
    Node startNode = grid.NodeFromWorldPoint(startPos);
    Node targetNode = grid.NodeFromWorldPoint(targetPos);

    List<Node> openSet = new List<Node>();
    HashSet<Node> closedSet = new HashSet<Node>();
    openSet.Add(startNode);

    while (openSet.Count > 0)
    {
        Node node = openSet[0];
        for (int i = 1; i < openSet.Count; i++)
        {
            if (openSet[i].fCost < node.fCost || openSet[i].fCost == node.fCost)
            {
                if (openSet[i].hCost < node.hCost)
                    node = openSet[i];
            }
        }

        openSet.Remove(node);
        closedSet.Add(node);

        if (node == targetNode)
        {

            return RetracePath(startNode, targetNode);
        }

        foreach (Node neighbour in grid.GetNeighbours(node))
        {
            if (!neighbour.walkable || closedSet.Contains(neighbour))
            {
                continue;
            }

            int newCostToNeighbour = node.gCost + GetDistance(node, neighbour);
            if (newCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour))
            {
                neighbour.gCost = newCostToNeighbour;
                neighbour.hCost = GetDistance(neighbour, targetNode);
                neighbour.parent = node;

                if (!openSet.Contains(neighbour))
                    openSet.Add(neighbour);
            }
        }
    }
    return null;
}


texts: I can't center my actors with ExtendViewport, Libgdx

texts:
I'm making a level select screen and I need use ExtendViewPort (I can't use Fit for other reasons), but this viewport moves my actors to the left, I need center them. I put X and Y position corresponding with my virtual screen size. This is my problem:

I do this things:

setViewport(new ExtendViewport(720, 1280));

@Override
public void resize(int width, int height) {
    levelsStage.getViewport().update(width, height, true);
}

actor.setPosition(10,100); (Examples..)

Sry for my bad english, I speak spanish.


texts:
I have a cube created in Unity scaled 5 times. The pivot of the cube is by default in center.

I would like to change the pivot to the one of the vertices.

How to do that ?