# Question
Title: Should I (and how to) avoid using global classes
I have been having fun learning java for years, did a little bit of OOP tutorials and this is the first time I attempt to make a real project. The project is very similar to some top down view tabletop management game with very little graphics. Oddly every thousand line of code I hit my head on a wall and wonder if I need to restructure everything. For example I restructured once to try and adopt some concept of MVC, which I had no knowledge of when I started. I am glad I did.

The wall now : I started reading how we should use global and singleton sparingly when I suddenly could not save my game since I had created a new instance that had static fields (using GSON to save my Game object).

## My project structure

* App : gameloop, has Engine class, calls Engine.updateUI() and engine.updateGame()
* Engine is the main controller that has access to all other controllers, creates the game object and updateUI() and updateGame() methods
* Game : contains every object that represent the state of the game so that I can save and load it
* MyData class is a global class that just loads a bunch of text files and provides data for the game but does not need to be saved

So lately I created a class called Finances that had static fields such as cash, waterBill, electricityBill... I can only ever need one instance of Finances in my game so I thought it would be neat to be able to do something like `Finances.addCash()` or `if Fiances.getCash() == enough doSomething` from anywhere in my code, from any controller, to enable and disable buttons for example.

I have another similar class called Updater that has static booleans as flags to schedule an update on certain part of the UI instead of having every UI elements update and query the model 60 fps.

## Some solutions

* Add some code to save and load the values of those static fields;
* change the fields to non-static and give Game another parameter called finances that will only be created once.

I was going with the second approach for a while but I realized I was just passing Engine engine everywhere to have access to everything like `engine.getGame().getFinances().getWaterBill().pay()`

I feel like this is just like a global variable but more complicated. Here I am not hoping to code the best code with the best structure and all best practices. I am just looking to improve and learn in a fun way. Most articles I found just end "anyway if you end up with needing many singletons or globals your code probably smells". That did not help me find a solution.

# Answer
Usually it's a good practise to avoid global variables/classes. The reason being, once you have a big enough project, and suddenly one global variable suddenly has a value that you didn't expect, how would you know who caused that? What if that result was caused from multiple places? It makes a big spaghetti mess.

There are ways to organise your code to avoid this, my favourite being Object-Oriented programming, where (in an ideal scenario) every object has access only to the data it needs to change and no more.

At the end of the day though, this is not a "black/white" thing, no answer is the best answer, and if you make a project full of singletons and global variables, but it works, does it really matter?
> 1 votes

# Answer
all that i can say is that you can use if it works for your project, for example if you are using a singleton and works for your game and it has better performance than to have many instances of that then i consider is ok, i suggest you to start implementing patterns where needed, i have an engine too and i have a Game class where i have the main loop/update there, i also have an util class where i have several methods to load resources ( pictures, sound, fonts, etc ), i have another class to process collisions and that is a singleton attached to the Game class so all levels can use the same instance to manage collisions. for controller i have another helper singleton class where i instantiate it, on game class and on each level depending if is a pause screen, menu or game play i just have different listeners for the same input, but at the end is the same class for all.

If you follow Java Best Practices then you will have a good project, try to follow the SOLID principle as well.
> 0 votes

---
Tags: java
---


# Question
Title: Use vsync event instead of a 16ms timer?
I found that in game development, most people set a timer that gets triggered every 16ms to do the rendering.

As an Android programmer, I'm familiar with the Choreographer. You set a callback that will do the drawing stuff, and each time vsync happens, the callback is called.

I know the original use of vsync is to prevent modifying the buffer when the front buffer and the back buffer are being switched. But don't you think making the drawing/render code have the same period as the actual screen refresh rate (in an ideal situation) is better?

So is there any reason why people don't prefer the vsync callback or vsync event based design?

One reason I can come up with is that if a monitor is 75Hz, it will be too high-frequency to do the rendering, right?

# Answer
> 2 votes
There are various reasons not to use the vsync event nowadays.

Indeed, historically when the games had to sync with the refreshrate of the screen because the ‘redraw’ would be visible or cause a flickering screen. At the vsync/vblank interrupt the game would switch between two memory buffers to prevent this.

A few reasons not to use the vsync:

**Physics engines like a fixed timestep**. In order to keep up with everything happening, games are often designed with a fixed physics timestep in mind: 60 or 30 physics frames per second. This is independent of the vsync and makes the physics engine happy. See also fix your timestep for more insight in this.

**system capabilities dictate the gamespeed** Many modern games have complex subsystems and complex graphics. Often the framerate is dictated by the system capabilities. If the system (CPU and GPU) can keep up, the game experience becomes smoother. These framerates are independent of the refreshrates. This is the variable timestep.

**Graphic cards can take care of vsync artifacts** Many graphic cards have technology onboard to cope with the need for vsync artefacts (for example Nvidia has ‘adaptive vsync’). This allows modern games to try and pump out as many frames as they wish without worry.

**Designed performance** Often games are simply designed with a framerate in mind. On consoles you often see 30fps or 60fps fixed timesteps. This helps game designers to determine how much scenary or gameplay elements they can have to meet their vision. This means they know everyone playing the game has the same experience and know exactly where the limits of their game engine is.

There may be more but these I can think of right now.

Note that there may be combinations of the above- having a game fixed at 30fps may still mean that you keep track of variable timesteps because something may cause unexpected slowdown. Another common option is to have fixed timesteps for physics simulation and variable timesteps for graphics.

Finally some systems still use the vsync to time the timesteps. It is still a viable method if you can guarantee your game can cope with the required updates/or the system simply dictates that method. Your Android reference is a good example and a valid method.

---
Tags: game-loop, timer, vsync
---


title: Adding large 3d models into Unity

text:
# Question
Title: Adding large 3d models into Unity
I have a 3d model of a restraunt with several characters in it probably over a hundred objects. Whenever I try to import it into Unity Unity just loads forever until I force close it. How do you import such large models without Unity crashing?

# Answer
Verify how many polygons your models have. High poly objects need more time and processor to load in scene. On Blender you can see the number of polygons on the top-right when in Edit Mode, and in Youtube you can see how to decrease the number of polygons with Blender. An other possible solution is import the model in parts. As I can see, you want to import a restaurant with a lot of models together. Divide and conquer. Try to separate the itens and import them separately.
> 1 votes

---
Tags: unity, 3d, graphics, models, blender
---


# Question
Title: Parallax background in with depth in Phaser 3
I'm working on a 2D space shooter type of game in typescript using Phaser 3 and am trying to get a parallax background with different depths going. But I'm having trouble getting the math right.

You can see my work in progress here: https://www.youtube.com/watch?v=Pea9yVbTD64

As stated in the video everything works if the players x and y are positive, but breaks when they are negative, and I can't figure out what I am doing wrong. Any help would be greatly appreciated. Or perhaps there is a better way to accomplish this?

What I'm doing is randomly generating out a bunch of the Sprites, storing them in an `Array`, and then updating their position with this code.

* **\_Nebulas**: is an `Array<NebulaParticle>`.
* **p.distance**: is a number between 1 and 5 to signify how far away the sprite is and is used to make them move slower when they are furher away.
* **\_Width** and **\_Height** are both arbitrary numbers to signify how big the area is that the parallax should cover, in the video they are both set to 80.
* **OriginalOffsetX/Y** is the original random position the Sprite was given.

(this line is here because the below code formatting wont work otherwise.)

```
public update(delta: number, playerx: number, playery: number) {
    console.log(playerx + ", " + playery );
    for (let i = 0; i < this._Nebulas.length; i++) {
        let p = this._Nebulas[i];
        p._Sprite.x = (playerx + (this._Width / 2)) - (((playerx / p.distance) + p.OriginalOffsetX) % this._Width);
        p._Sprite.y = (playery + (this._Width / 2)) - (((playery / p.distance) + p.OriginalOffsetY) % this._Height);
    }
}

class NebulaParticle {
    public _Sprite: Phaser.GameObjects.Sprite;
    public OriginalOffsetX: number;
    public OriginalOffsetY: number;
    public distance: number;
}

```

# Answer
Just use a camera with the gameobject method `setScrollFactor`. Setting 0 makes it fixed to the camera; setting a number between 0-1 will make it scroll at varying rates, which you can use to set up parallax scrolling layers.

See an example here
> 0 votes

---
Tags: phaser, typescript
---


# Question
Title: How do I slow down time without affecting the player? (shortened question to ONLY the code and its bugs)
how do i slow down time without slowing down the player as when i tried to implement my own version

```
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

namespace UnityStandardAssets.Characters.FirstPerson
{
    [RequireComponent(typeof(Rigidbody))]
    [RequireComponent(typeof(CapsuleCollider))]
    public class JumpingPhysics : MonoBehaviour
    {
        [Serializable]
        public class AdvancedSettings
        {
            public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
            public float stickToGroundHelperDistance = 0.5f; // stops the character
            public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
            public bool airControl; // can the user control the direction that is being moved in the air
            [Tooltip("set it to 0.1 or more if you get stuck in wall")]
            public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
        }

        private float m_YRotation;

        private Rigidbody m_RigidBody;
        public bool m_PreviouslyGrounded, m_IsGrounded;
        public Vector3 m_GroundContactNormal;
        private CapsuleCollider m_Capsule;
        public AdvancedSettings advancedSettings = new AdvancedSettings();
        public float verticalVelocity = 0f;
        public float gravity = 9.80665f;
        public float jumpForce = 20.0f;
        public float MovementSpeed;
        public float MovementSpeedDefault = 10f;
        public float forces = 10.0f;
        public float drag = 10.0f;
        public CharacterController controller;
        public float slowdownFactor = 0.005f;
        public float Matrix_Time = 0;
        public float Time_Original = 0;
        public bool Matrix = false;
        public bool Matrix_Instant_Time = true;
        public int Matrix_State = 0;

        public void DoSlowmotion()
        {
            Matrix_State = 2;
            Matrix_Time = slowdownFactor;
            Time.timeScale = Matrix_Time;
        }

        public void DoSpeedUp()
        {
            Matrix_State = 3;
            Matrix_Time += (1f / 1f) * Time.unscaledDeltaTime;
            Matrix_Time = Mathf.Clamp(Matrix_Time, 0f, 1f);
            Time.timeScale = Matrix_Time;
            if (Matrix_Time >= Time_Original) Matrix_State = 0;
        }

        public void DoSlowDown()
        {
            Matrix_Time -= (1f / 1f) * Time.unscaledDeltaTime;
            Matrix_Time = Mathf.Clamp(Matrix_Time, 0f, 1f);
            Time.timeScale = Matrix_Time;
            if (Matrix_Time < slowdownFactor) Matrix_State = 1;
        }

        public void Start()
        {
            if (Matrix_Time == 0) Matrix_Time = Time.timeScale;
            if (Time_Original == 0) Time_Original = Time.timeScale;
            MovementSpeed = MovementSpeedDefault;
            m_RigidBody = GetComponent<Rigidbody>();
            m_Capsule = GetComponent<CapsuleCollider>();
            controller = GetComponent<CharacterController>();
        }

        private Vector3 moveDirection = Vector3.zero;

        private void Update()
        {
            Update1();
        }

        private void Update1()
        {
            GroundCheck();
            InteractRaycast();
            if (controller.isGrounded)
            {
                moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
                moveDirection = transform.TransformDirection(moveDirection);
                moveDirection *= MovementSpeed;
                if (Input.GetButton("Jump")) moveDirection.y = jumpForce / Matrix_Time;
                MovementSpeed = MovementSpeedDefault / Matrix_Time;
            }
            else
            {
                moveDirection.y -= (gravity * Time.fixedUnscaledDeltaTime) / Matrix_Time;
            }
            verticalVelocity = moveDirection.y;
            controller.Move(moveDirection * Time.fixedDeltaTime);
            if (Input.GetButtonDown("Matrix")) Matrix = !Matrix;

            if (Matrix)
            {
                if (Matrix_Instant_Time)
                {
                    if (Matrix_State == 0) DoSlowmotion();
                }
                else
                {
                    if (Matrix_State == 0 || Matrix_State == 3) DoSlowDown();
                    if (Matrix_State == 1) DoSlowmotion();
                }
            }
            else
            {
                if (Matrix_Instant_Time)
                {
                    Matrix_Time = Time_Original;
                    Time.timeScale = Matrix_Time;
                    Matrix_State = 0;
                }
                else DoSpeedUp();
            }
            Time.fixedDeltaTime = Time.timeScale * .02f;
        }

        private Vector2 GetInput()
        {
            Vector2 input = new Vector2
            {
                x = CrossPlatformInputManager.GetAxis("Horizontal"),
                y = CrossPlatformInputManager.GetAxis("Vertical")
            };
            return input;
        }

        /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
        private void GroundCheck()
        {
            RaycastHit hitInfo;
            if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                ((m_Capsule.height / 2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
            {
                m_IsGrounded = true;
                m_GroundContactNormal = hitInfo.normal;
            }
            else
            {
                m_IsGrounded = false;
                m_GroundContactNormal = Vector3.up;
            }
        }

        void InteractRaycast()
        {
            Vector3 playerPosition = transform.position;
            Vector3 forwardDirection = transform.forward;
            Ray InteractionRay = new Ray(playerPosition, forwardDirection);
            RaycastHit InteractionRayHit;
            float InteractionRayLength = 5.0f;

            Vector3 InteractionRayEndpoint = forwardDirection * InteractionRayLength;
            Debug.DrawLine(playerPosition, InteractionRayEndpoint);

            bool hitfound = Physics.Raycast(InteractionRay, out InteractionRayHit, InteractionRayLength);
            if (hitfound)
            {
                GameObject hitGameObject = InteractionRayHit.transform.gameObject;
                string hitFeedBack = hitGameObject.name;
                printfTools.Tools.fprintf(Debug.Log, "FPRINTF raycast hit object with name %s", hitFeedBack);
            }
        }
    }
}

```

i encounter the following bugs

when jumping then slowing down time, my character jumps at a lower height, due to the jumpforce not scaling with timescale

when jumping then speeding up time my character jumps WAY higher than normal

when falling and slowing down time my character slows down then speeds back up to normal

when falling and speeding up time my character falls WAY faster than it normally should

when moving and speeding up time my character zooms forward for a bit then moves normally

when slowing down time beyond 0.005, eg 0.004, the movement code that balances the player speed with the time scale becomes unreliable as the player will move faster than they are supposed to, which should not happen

these bugs should not be happening yet they are and i do not know how i would fix them

# Answer
> 1 votes
You could setup a table of delta time multipliers and have your objects read off those based on their assigned groups.

So you'd have something like

```
mySpeed = velocity * Time.delta

```

but instead do

```
mySpeed = velocity * TimeTable.get(PlayerTimer);

```

PlayerTimer would then be an enum of some sorts.

The get function would be something like:

```
float get(myEnumType group){
     return Time.delta * timetable[group];
}

```

where timetable is a `map<myEnumType, float>`;

```
float set(myEnumType group, float multiplier){
     timetable[group] = multiplier;
}

```

Downside of course is it's a bit more management. Unless you only have a few groups it should be fine.

---
Tags: unity
---


# Question
Title: Can I publish a game on Steam while obscuring my personal identity from the public?
I'm looking to publish a game on Steam that contains explicit adult content.

I am seeking to make this a hobby that earns passive income as opposed to pursuing it as a full time job. I would prefer that a prospective employer could not easily track my name back to this game and thus not consider me for the job.

I have read the Steamworks Partner Program here:
https://partner.steamgames.com/steamdirect

And thus understand that for Steam's sake, I will need to identify myself. But can I publish under some sort of pseudonym to prevent a simple Google Search of my name from returning this game? Or will this pretty much be on my so-called "permanent record" for life?

# Answer
Publish your game through a company that you've created rather than directly.

This probably won't make it *completely impossible* for a dedicated sleuth to associate your person with the organization, but it should make it sufficiently difficult that most people won't even try, especially if you are able to engage the services of a third party (such as a law firm) to act as the registered agent of the company.

The details of forming the corporate entity vary by location (as do the types of entities available) so you may need to consult your local government's documentation on the subject.
> 6 votes

# Answer
Another option would be to release the game through a publisher. Ask one of the established developers in that niche if they would like to partner with you. This will likely be a win-win situation for both of you, because both of your games will benefit from cross-promoting each other. Assuming that your games appeal to the same target audience and have about the same level of quality, of course.

Note that in that case Steam will pay the earnings from your game to the publisher, not to you. So you need to make sure you can trust them to hold up their part of the bargain (whatever it is you negotiated).

Also keep in mind that your publisher might agree to conceal your identity from Valve and from the general public, but they are unlikely to protect you in case of any legal issue.
> 1 votes

---
Tags: steam, publishing, business
---


# Question
Title: How To Add Animation Graphics To An Android Game
How to make something like this animation drawings that coming out from the car ?

(I'm using android studio)

The Game's Link : Finger Driver

# Answer
As it has been already mentioned in the comments, this effect is called "Particle System".

What it does, basically, is spawn multiple objects over a period of time, and each object has a small animation before it "dies". I haven't played the game on your screenshot, but from what I can tell, in this case, the particle system is attached on the car, and every so often spawns a circle with a specific size. Each circle spawned this way, keeps decreasing in size, until they reach 0 in which case they destroy themselves.

There is no "right" or "wrong" way to make something like that. You can either create a simple particle system yourself, or you can use a library which already includes a solution for it.
> 1 votes

# Answer
I think the best way to achieve this will be to use a sprite sheet and use Rect to show different areas of the sheet quickly (giving the illusion of movement/ animation). I think this article will be of use to you.
> 0 votes

---
Tags: android, animation, graphics-programming, particles, android-studio
---


# Question
Title: Pathfinding How to store data for big terrain size
I am trying to implement my own pathfinding solution in unity but cant figures out how to store data. Following is my grid class which stores height, length and neighbour tile of tile.

```
public class grid
{
public float XVal;
public float ZVal;
public int[] NId = new int [8];
}

```

With Length and Height of 1, I am creating a grid for terrain size that part of the code works nicely It creates a grid, finds its neighbours. I am saving data in Array

```
grid[] MyGrid ;

```

The problem occurs when terrain size is big ex 1024\*1024 so for creating a grid, Considering row and column of terrain total elements of grid becomes row(1024)\*column(1024) approx. 1 million. As creating such a big grid while running game is impossible So I created custom inspector and generate grid graph and populate array in the editor. But while loading game as Mygrid array size is 1 million game stucks while loading, To fix that I created subsystem which basically divides Mygrid array in multiple arrays which seems working but is there any other way to efficiently store grid data as dividing array adds complexity in code

# Answer
> 4 votes
Right now for each tile you're storing:

* 4 bytes of x position
* 4 bytes of y position
* an array of neighours, entailing...
    + 32 bytes of IDs
    + 4+ byte address of the array
    + 4 byte array size
    + ? memory management overhead
* 4+ byte address of this grid cell in you myGrid array
* ? memory management overhead for this instance of the class

That's something over 50 bytes to store one bit of information: "this spot is navigable," and that means your 1024x1024 map uses over 50 megabytes of memory.

By contrast, we could store navigable/not navigable as a 0 or 1 bit in a sequence of bits. We know which tile a given bit is describing, and which 8 tiles are its neighbours, based on its position in the sequence.

For example:

```
public class BitGrid {
    int size;
    BitArray bits;

    public BitGrid(int size) {
        this.size = size;
        bits = new BitArray(size * size);
    }

    public void SetPassable(int x, int y, bool isPassable) {
        int index = CellToBitIndex(x, y);
        if(index < 0)
            return;

        bits[index] = isPassable;
    }

    public bool IsPassable(int x, int y) {
        int index = CellToBitIndex(x, y);
        if(index < 0)
            return false;

        return bits[index];
    }

    int CellToBitIndex(int x, int y) {
        if(x < 0 || x >= size || y < 0 || y >= size)
            return -1;

        // If desired, you could instead use Morton Ordering
        // here for better data locality between rows.
        return y * size + x;
    }
}

```

Now the pathfinder operates on ordered pairs of `x, y` coordinates (or x z if you prefer), and can query neighbours by checking `myGrid.IsPassable(x-1, y-1)` etc.

Doing it this way the 50 meg map takes only 128 KiB of memory, at least 400 times smaller. And it can be stored contiguously so we don't encounter so many cache misses from jumping around memory following pointers.

I'd suspect this method will run much faster and allow you to scale up to even larger maps if you choose.

# Answer
> 0 votes
Similar to what DMGregory mentioned, you have lots of memory overhead for things that can be mathematically determined (with a little bit of architecture changing).

First off, your grid data structure is ENTIRELY data. If you typed your data as a struct rather than a class c# wouldn't need to create additional memory management data (ptrs, reference counters, etc) per grid instance, which could save a decent chunk of memory.

Since you keep using the word "grid" I'm going to assume that's the general structure of your tiles. If that's the case, you may be better off using grid indices as a "hash" of vector2 information, resulting in a byte\[\]\[\] to store terrain information. This way a tile's position AND neighbor information is exposed as part of the structure rather than data that needs to be loaded / saved. This saves you tons of memory and has potential performance improvements.

If you can't use a 2D array, consider splitting your data into separate structures, using a more "data oriented approach". So you'd have a Vector2\[\] for position data and an int\[\]\[\] for neighbor information. This doesn't necessarily save you space, but it might due to data alignment. It also has potential runtime benefits.

---
Tags: unity, ai, path-finding
---


# Question
Title: How to panning camera on XZ axis with different angles
I have an Orthographic camera where the position is `{ x:0, y:100, z:0 }` and is pointing/looking at `{ x:0, y:0, z:0 }`. At this point, I'm able to capture the mouse movement and translate it to make the pan correctly. If the mouse goes 10 px down/y I just have to move Z in the 3D world.

The problem is that I don't know how to calculate if the camera position is in perspective, let's say:

```
position: { x:50, y:50, z:50 }
lookAt: { x:0, y:0, z:0 }

```

I guess I have to use some trigonometry, but I'm very lost, to be honest. Any guide would be very helpful.

# Answer
You can construct the camera's forward direction vector as:

```
forward = normalize(lookAt - position)

```

Then you can construct a vector pointing to the camera's right like so:

```
right = normalize(cross(worldUp, forward))

```

(Or the negation of this if you're in a right-handed coordinate system)

And lastly you can construct a vector pointing along the camera's local up direction like so:

```
up = cross(forward, right)

```

(Again, negate if you're in a right-handed coordinate system)

Then you can pan the camera by adding a multiple of these `right` and `up` vectors to its position. You'll likely want to move the lookAt point by the same amount, unless your goal is to orbit around the point.
> 2 votes

# Answer
Here is the code explained by @DMGregory in Three.js

```
function panCamera({ position, lookAt, x, y }) {
    const worldUp = new THREE.Vector3(0, 1, 0).normalize()
    const distance = lookAt.clone().sub(position).normalize()
    const right = distance.clone().cross(worldUp).normalize()
    const up = distance.clone().cross(right)
    right.multiplyScalar(-x)
    up.multiplyScalar(-y)
    position = position.clone().add(right).add(up)
    lookAt = lookAt.clone().add(right).add(up)
    return { position, lookAt }
}

// Usage
const x = 5 // user moves 5px the mouse to the right
const y = 10 // 10px to the bottom

// getting a new position and lookAt
const { position, lookAt } = panCamera({
    position: new THREE.Vector3(50, 50, 50), // perspective example
    lookAt: new THREE.Vector3(0, 0, 0),
    x, y
})

// Applying new cordinates
camera.position.set(position.x, position.y, position.z) // we can't just pass position as an argument :(
camera.lookAt(lookAt)

```

Here a full example with zoom using d3 to capture the mouse gestures: https://codepen.io/josema/pen/zMeNry?editors=0010
> 0 votes

---
Tags: camera, mouse, trigonometry
---


# Question
Title: How can I pack repeated textures into one texture efficiently?
I have an obj mesh with some textures, several of them are repeated(uvs are not within \[0,1\]). I'd like to merge all those textures into one texture and transform the uvs of obj.

# Answer
Since the question is about "efficiently" packing a mix of repeated and non-repeated textures into a texture atlas, the answer is: most likely no, you can't. As DMGregory said Texture Arrays are probably the way to go instead.

## Why:

If you want to go the atlas way **you will have to slice triangles on UV repeat edges** (edges in texture space) but this may significantly increase your mesh complexity, increasing geometry workload.

And this has repercussions for linear interpolation, including mip-maps.

This means you'll need to add a repeated border at least 2^(n+1) pixels thick where n is the number of mip-map levels you want.

Unless you're making a voxel engine or GUI engine that would otherwise cause massive amount of texture switches there isn't a gain to be had. As long as the GPU can handle the number of textures being sampled in a single object there isn't a real benefit to creating an atlas.

At the shader level sampling 4 different texture or sampling a single texture atlas 4 times makes no difference to a modern GPU of at least the last 10 years.

The only saving might be the removal of 3 tiny "Set Texture Sampler {X} to Texture {Y}" commands from the GPU command stream.

If you gain any benefit at all from this you will likely gain a higher benefit by making sure all your objects using the same material are rendered at once without switching materials / GPU render states. Making the atlas packing gains insignificant.

Large texture atlases also prevent some GPUs from efficiently managing GPU RAM as some need to transfer entire textures to GPU RAM before running the shader.

So while automatically-generated texture atlases make sense for GUI text or 2D tile / 3D voxel massively-tile-based renderer, it does not make so much sense for characters.

The usual way to go is to bake (combine) the complex textures layers into simpler unwrapped textures using a capable 3D modeling/painting software.
> 1 votes

---
Tags: textures, texture-atlas, rendertexture
---


# Question
Title: LOD culled gameobject still interacts with raycast
The camera is sort of top down and the player can move objects around, rotate them, delete them etc. I use a raycast to check what was hit when the player clicks. But some objects are culled by the LOD group when far away, but the LOD group only disables the renderer, not the colliders, so it still interacts with the raycast. This means a player can move or delete an object that they can't even see.

I've tried looping through all the renderers in the lod group and using renderer.isVisible but it doesn't solve the problem of collision and raycasts. I'd really rather not poll isCulled every frame in update either because there are thousands of gameobjects, that would be horrible for performance.

```
LODGroup lodGroup = GetComponent<LODGroup>();
LOD[] LODs = lodGroup.GetLODs();
for (int i = 0; i < LODs.Length; i++)
{
    LODRenderers = LODs[i].renderers;
}

bool isCulled = true;

for (int i = 0; i < LODRenderers.Length; i++)
{
    if (LODRenderers[i].isVisible)
    {
        isCulled = false;
    }
}

```

# Answer
Solved over here: https://forum.unity.com/threads/lod-culled-gameobject-still-interacts-with-raycast.593410/

Basically RaycastAll or RaycastNonAlloc is used because they do not stop the raycast when a object is found, they return all the objects in the path of the raycast. I then sort them by distance, checking that they are visible at the same time.

I'll copy the code here for convenience.

```
float minDist = Mathf.Infinity;
int minDistIndex = -1;

for (int i = 0; i < m_RaycastHits.Length; i++)
{
    if (m_RaycastHits[i].collider == null)
        continue;

    if (m_RaycastHits[i].distance < minDist)
    {
        Element element = m_RaycastHits[i].collider.GetComponent<Element>();

         if (element.IsCulled)
             continue;

         minDist = m_RaycastHits[i].distance;
         minDistIndex = i;
    }
}

if(minDistIndex != -1)
{
    //do something with m_RaycastHits[minDistIndex]
}

```
> 0 votes

# Answer
Use is render visible via transform:

```
 LODGroup groupLOD = obj.GetComponent<LODGroup>();
 if (lodGroup != null)
 {
     Transform lodTransform = groupLOD.transform;
     foreach (Transform child in lodTransform)
     {
         var renderer = child.GetComponent<Renderer> ();
         if (renderer != null && renderer.isVisible)
         {
             Debug.Log("current lod is" + child.name);
         }
     }
 }

```
> 0 votes

---
Tags: unity, c#, level-of-detail
---


# Question
Title: Determining which way a wall faces in a 2D grid with minimal boilerplate
I have a 2D grid of quadrilateral tiles, some of which are walls, some are floor; each tile has four vertices, which are shared with the tiles around it (so each rendered "wall" is at least two wall-tiles thick). In order to render this scene, I need to know, for each tile:

* is it a wall?
* if so, is it a straight wall, a convex corner (pointing outwards), or a concave (inwards) corner? (so that I can select an appropriate texture to use – for the sake of example, ignore tiles that are totally surrounded by walls)
* which direction is the free space in? (so that I can rotate the texture correctly)

e.g. for tile `@` with walls `W` and floor `.`, this would render a straight wall facing east:

```
WWW
W@.
WWW

```

whereas this would be a convex corner facing north-west:

```
...
.@W
.WW

```

Some more interesting arrangements: this would ideally be treated as a special case (with a valley down the middle of two walls):

```
WW.
W@W
.WW

```

and something like this would ideally be two convex corners at `A` and `B`, as if there were two independent 2x2 squares of walls:

```
WW..
WABW
..WW

```

I'm not worried about handling invalid patterns of walls (e.g. a cross-shape of 5 walls) for now.

It's easy to track whether each tile is a wall or not, but I don't see a clean way to determine the other two conditions from that data. Is there a nice algorithm to do this without enumerating every possible arrangement of neighbouring tiles?

# Answer
> 0 votes
It sounds like what you are attempting is the Marching Squares algorithm.

You define a M x N grid of points. For each point, you define whether it is 'inside' or 'outside' a wall.

With this, you can generate a world, sized M-1 x N-1, built with your tiles.

The marching squares algorithm will tell you which tile to use at each position based on its four corner values.

Writing a marching squares algorithm is pretty trivial, by the way. Here's my Python implementation.

---
Tags: python, panda3d
---


# Question
Title: PVRCT Texture Format with glTexStorage2D on Open GL 3.0 ES How?
I've looked everywhere and I can't seem to find the answer.

How can I use glTexStorage2D with PVRCT textures? I've done this:

```
#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02

glTexStorage2D(GL_TEXTURE_2D, 1, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, m_uPixelsWide, m_uPixelsHigh );

```

Where the GL\_COMPRESSED\_RGBA\_PVRTC\_4BPPV1\_IMG internal format works for glTexImage2D, but when I run that Tex Storage command, my pvr textures come out black. There are no errors posted, and when I query glGetTexParameteriv, my texture is indeed set to Immutable.

Does PVRCT not work for opengl 3.0?

# Answer
Have you checked the Opengl ES 3.0 documentation on glTexStorage2D?

According to the docs:

> internalformat must be one of the sized internal formats given in Table 1,
> or one of the compressed internal formats given in Table 2 below.
> Upon success, the value of GL\_TEXTURE\_IMMUTABLE\_FORMAT becomes GL\_TRUE.

There is no macro for PVRCT in table 1 or 2.

Also have a look at the Apple documentation on PVRCT compression.

According to the docs, the PVRCT format you've cited is used with the
following two Opengl ES functions:
\- glTexImage2D
\- glCompressedTexImage2D

Both of these functions are used to specify a two-dimensional texture image.
(where as glTexStorage2D specifies the storage for all levels)

Another note from the Apple documentation:

> PVRTC textures must be square. The width/height must be a power of two.

Might be a good idea to check that your textures match this requirement.
> 1 votes

---
Tags: textures, opengl-es
---


# Question
Title: Rendering clouds similar to Sky: Light Awaits?
I'm interested in adding clouds to my game, with a style similar to those in Sky: Light Awaits

You can see them in motion in these videos:

The cloud rendering in this game really is fascinating but meanwhile efficient enough to be run on mobile platforms.

How could I do something like this in my own game?

# Answer
You could hack some glsl fragment shader to do something like that, I've posted a Shadertoy that does what you want:  It consists of a faked simulation, a Fractional Brownian Motion rendered through a Sphere Tracing Algorithm that accumulates at each step when it hits the fbm function.

You could do much better, but since you are asking for something performant, I think that this would suffice, if you are willing to go further you could do the techniques mentioned by Guerrilla Games on Horizon Zero Dawn in which they do a mix between Worley, Perlin and Curl noise.

The first step is getting the Fractal Brownian Motion, to do so we can either compute the noise in the GPU like this:

```
// Function courtesy of IQ.
float noise( in vec3 x )
{

    vec3 p = floor( x );
    vec3 k = fract( x );

    k *= k * k * ( 3.0 - 2.0 * k );

    float n = p.x + p.y * 57.0 + p.z * 113.0;

    float a = hash( n );
    float b = hash( n + 1.0 );
    float c = hash( n + 57.0 );
    float d = hash( n + 58.0 );

    float e = hash( n + 113.0 );
    float f = hash( n + 114.0 );
    float g = hash( n + 170.0 );
    float h = hash( n + 171.0 );

    float res = mix( mix( mix ( a, b, k.x ), mix( c, d, k.x ), k.y ),
                     mix( mix ( e, f, k.x ), mix( g, h, k.x ), k.y ),
                     k.z
                     );

    return res;

}

```

Or get the noise from a texture, like this:

```
// Function also courtesy of IQ.
float noise( in vec3 x )
{

    vec3 p = floor(x);
    vec3 f = fract(x);
    f = f*f*(3.0-2.0*f);

    vec2 uv = (p.xy+vec2(37.0,17.0)*p.z) + f.xy;
    vec2 rg = textureLod( iChannel0, (uv+ 0.5)/256.0, 0.0 ).yx;
    return mix( rg.x, rg.y, f.z );

}

```

Here is a link for you to check Iñigo Quilez but if you are asking for something glsl related you probably know who this guy is.

If you are interested in getting the most bang for the buck, you'll go for the non-procedural approach, here is the texture:

Remember that you must not VFlip it or it won't work.

Now that we have our noise, we want to create our fbm, it consists of multiple copies of noise stacked together at different octaves, with different amplitudes and frequencies, here is a function that does that while moving at different speeds in each of the octaves:

```
// Here we do the stacking of noise at different octaves.
float fbm( in vec3 p )
{

    float f = 0.0;
    f += 0.5000 * noise( p ); p *= 2.02; p -= iTime * 0.05;
    f += 0.2500 * noise( p ); p *= 2.03; p += iTime * 0.025;
    f += 0.1250 * noise( p ); p *= 2.01; p -= iTime * 0.01;
    f += 0.0625 * noise( p );
    return f / 0.9375;

}

```

For this case I prefer the function that I just mentioned, for the possibility of moving the noise at different octaves at different speeds, but this one is more succinct:

```
float fbm( vec3 p )
{

    float result = 0.0;
    float m = 0.0;

    float amplitude = 1.0;
    float freq = 1.0;

    // Change the 5 for less or more iterations, I just learnt that
    // it's more performant to not store the stop condition in a
    // variable https://stackoverflow.com/questions/2614622/tips-for-efficient-glsl-code
    for (int i=0; i<5; i++)
    {
        result += noise( p * freq ) * amplitude;

        m += amplitude;
        amplitude *= 0.5; //lacunarity
        freq *= 2.0; //gain
    }

    return result/m;

}

```

With our fbm ready we can compute our map function, that we will need later for our ray function, it goes something like this:

```
float map( vec3 p )
{

    // We store our fbm value in our variable f, note that we added a
    // frequency perturbation to p (Position), to get a more realistic
    // look.
    float f = fbm( p * 1.5 );

    // We only want to get a plane so we only use the y component of
    // our p variable, note that in a normal rayMarching function, it
    // would be p.y - 1.0 to move our geometry, in a volumetric
    // ray marching we must do 1.0 - p.y.
    // After we get our plane we must protrude it by our fbm.
    return 1.0 - ( p.y + f );

}

```

Now is time to do the Ray Marching, for this case we want a specialized function that handles volumetrics:

```
// The variable den, for density stores a float that will keep track of
// of guess what, density, we get it by overloading it with our map
// function that basically stores the computing of the fbm function,
// it only adds a bit of frequency for a more realistic look.
float ray( vec3 ro, vec3 rd, out float den )
{

    float t = 0.0, maxD = 0.0; den = 0.0;

    // To be able to change the number of iterations we would have not
    // only to modify the 32, but also the quantity that we add to t,
    // for example change 32 to 16 and t += 0.05 to t += 0.1
    for( int i = 0; i < 32; ++i )
    {

        // p for Point is where we are in our virtual world.
        vec3 p = ro + rd * t;
        // We weight down our density for visual purposes, the 0.6 is
        // what they call a "magic number".
        den = 0.6 * map( p );
        // maxD for maxDensity, keeps track that we don't have negative
        // numbers in our density.
        maxD = maxD < den ? den : maxD;
        // We bail if we have a density of more than 1 or if our
        // rayMarchingSteps t is bigger than our threshold.
        if( maxD > 1.0 || t > 5.0 ) break;
        // We iteratively add a 0.05 to our RayMarching steps t.
        t += 0.05;

    }

    den = maxD;
    return t;

}

```

The only important part that we are missing is the shading, we will call this function shad, here is a snippet of code:

```
vec3 shad( vec3 ro, vec3 rd )
{

    // We retrieve our density from our ray function.
    float den = 0.0;
    float t = ray( ro, rd, den );

    // We will interpolate linearly, our magic vec3's: colour one and
    // two, and we will do so according to our density.
    vec3 col = mix( vec3( 0.5, 0.1, 0.1 ), vec3( 1 ), den );

    return col;

}

```

Final steps, in our main function, we can do the interpolations according to our UV's y so that we can get a gradient to our background.

```
/* This goes in main */

// bac for backGround stores the colours that we want our background
// to have, we interpolate according to uv.y to get our gradient.
vec3 bac = mix( vec3( 0.1, 0.4, 0.6 ), vec3( 0.31, 0.53, 0.7 ), -uv.y );
vec3 col = mix( bac, shad( ro, rd ), den );

// And finally we want a cheap and dirty gamma correction.
col *= sqrt( col );

```
> 2 votes

---
Tags: shaders, rendering, glsl, graphics-programming, raymarching
---


title: Where do components get added in Unity?

text:
# Question
Title: Where do components get added in Unity?
In unity's GameObject class, there are a few default data members. When we add a component to the game object, light for example, where exactly does it get added? Does it become a part of the GameObject class?

# Answer
> 0 votes
In the past, components used to be added to the GameObject itself, in such a way, that you could call `myGameObject.renderer` to get an object's `Renderer`.

This however changed to the call of `myGameObject.GetComponent<Renderer>()`, which hides the details of where the components are saved, which shouldn't be relevant anyway. Since for most (if not all) cases it doesn't matter for the user where components are, but that they belong to an object.

As @DMGregory noted, when you (used to) refer to a component with the first way (`myGameObject.renderer`) it acts like a getter behind the scenes, so the `GetComponent` function just replaced that, it still seems to work the same way, as in, you can get a component from a `GameObject` but the implementation details are unclear and not needed.

---
Tags: unity
---


# Question
Title: Not getting proper height in unity when android device has notch or navigation bar on screen
`Screen.height` is not giving the proper resolution of an Android device when that device has a notch or navigation bar.

Due to this there is offset at bottom of screen:

Here I have set the Admob banner to display at the bottom. But it shows with some offset away from the bottom edge of the screen.

How can I get the proper height of the device in Unity and work with the notch on devices that have them?

# Answer
> 1 votes
`Screen.height` returns the amount of pixels on the screen that are available to your app. In older versions of android the navigation bar would always remain static on the screen, eating a portion of it. This means that any app that runs does not have access on that portion of the screen. That is not an error, it's how the Android OS works, and in my opinion, it's the correct thing to do.

In newer versions, the navigation bar can get minimised if your app is set to run as fullscreen, which gives you access to the whole screen.

You also mention this causes a gap on the bottom of your screen. It's unclear why, unfortunately I can't give a solution to that unless you want to share some screenshots of what you mean.

---
Tags: unity, android, screen
---


title: Fire at enemy script doesnt work

text:
# Question
Title: Fire at enemy script doesnt work
I need my enemies to fire at me. I have a script and I think all is correct. I couldnt figure out why it doesnt work?

```
public class AntagonisticElCreator : MonoBehaviour {

public GameObject boom;
public float enemySpeed;

public bool move=false;
public bool shoot=false;
public Transform character;
Vector3 pos;
int boomnumber;

 public float bulletSpeed;
public float bulletDestroyTime;

public GameObject bulletPrefab;
public Transform bulletSpawn;

void Start () {
   bulletSpeed = 15f;
bulletDestroyTime = 8f;
    NumbarofBullet = 105;
}

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

    pos = new Vector3(character.position.x, transform.position.y, character.position.z);
    distance = Vector3.Distance(transform.position, character.position);
    if (distance < 20){
        move = true;
        shoot = false;
        transform.LookAt(pos);

    }
    if (distance < 10)
    {
        move = false;
        shoot = true;

    }

    if (move)
    {
        transform.position = Vector3.MoveTowards(transform.position, character.position, enemySpeed * Time.deltaTime);
        transform.LookAt(pos);
    }
    if (shoot)
    {
        shootAt();
    }

        void shootAt(){

        Instantiate(explsn, bulletSpawn.transform.position,
        bulletSpawn.transform.rotation);
      var bullet = Instantiate(bulletPrefab, bulletSpawn.position,
      bulletSpawn.rotation);
        bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward *
        bulletSpeed;

}

}

```

* \*/

# Answer
You are trying to define a new method within the code of another method. C# does not allow you to do that until version 7.0 (which the current Unity version 2018.2 doesn't support yet).

Move the definition of the `void ShootAt` method out of the `void Update` method so it's a private method within the `class AntagonisticElCreator`.
> 3 votes

# Answer
i can see the following

1. Is this the whole script? And if so is it getting any errors? Cause i see for example that distance is not declared and the shootAt() function is inside Update().
2. Declare your distance variable.
3. Try to make the initializations in the Start() and not in the Class body. ( example. public bool move=false; )
4. In your Update(), i guess pos is the position of the character. Please check your Y axis input here ( you get x,z from character but y from enemy)

Nik
> 0 votes

---
Tags: unity, c#
---


title: Position object in FOV in threejs

text:
# Question
Title: Position object in FOV in threejs
I'm just starting with threejs, and I'm building a basic first person shooter. I use pointer lock controls.

When the user clicks ("shoots") an object, I remove it and place it at another random position in the 3D world.

When creating the object, I want to position the object randomly, but always *inside the current field of view of the user*. So the object must be visible in the current view of the user when it's created.

I've tried things like `h = tan(fov/2)*dist` trying to get the height, but the problem is I don't have the distance between the object and the camera, since the object still needs to be created...

Any help would be much appreciated. I've found similar questions online, but they're usually about changing the camera view based on an object, but that's not what I want since the camera view is determined by the mouse of the user.

# Answer
You need the camera's properties for the following formula, mainly the angles of the camera, the position of the camera, vertical FOV, the aspect ratio (width / height), the near and the far clipping plane's distance.

Getting an angle that's inside the camera's view is very simple, you just use the vertical FOV, get a random value between 0 and it (I refer to this as `yAngle`), then calculate the horizontal FOV (vertical FOV * aspect ratio), create a random value between 0 and that too (this'll be `xAngle`), then you add the camera's rotation around the y axis (yaw) to the horizontal angle, and the camera's rotation around the x axis (pitch) to the vertical angle (these are xTotal and yTotal respectively).

Now you have the angles. You need to get the distance between the object and the camera. This should be a random value between the near and far value. Lastly, you need to create a vector out of this. There are multiple ways this can be done. You can either use this formula, or you can create a vector pointing in the negative z direction, then create a rotation matrix (the 2 methods do the same, the first one is just the algorithm version of the latter one).

After you got the vector, you can add it to the position of the camera and done, you get a position in the field of view of the camera.

Pseudo-code:

```
func getPosition(float FOV, float aspect, float cameraXAngle, float cameraYAngle, float near, float far, vec3 cameraPos) {
    xTotal := rand(0, FOV * aspect) + cameraXAngle
    yTotal := rand(0, FOV) + cameraYAngle

    distance := rand(near, far)

    vec3 direction = vec3(
        distance * cos(xTotal) * sin(yTotal),
        distance * cos(xTotal) * cos(yTotal),
        distance * sin(xTotal)
    )
    return cameraPos + direction
}

```
> 1 votes

# Answer
> I've tried things like h = tan(fov/2)\*dist trying to get the height, but the problem is I don't have the distance between the object and the camera, since the object still needs to be created

Well, you need to first randomly choose a `dist` value then. There's `N^3` more space as you go `N` times further away, so picking something like `dist = pow(1 - rand()/RANDMAX, 3) * max_dist` should result in a believable distribution.
> 1 votes

# Answer
I'm not familiar with three.js, but from my experience with 3D graphics, there's a simple trick you can try.

When you create a new object, move it to the camera's position, and copy the camera's rotation, this way the new object will "look" towards the same place as the camera.

Now translate the object on the +Z axis (or -Z, depending what three.js considers forward), and it will move forward inside the field of view. All 3D engines I've used have a translate function that does the math for you.

A quick search on StackOverflow, shows this solution:

```
object.translateZ( 10 );

```

Replace `10` with any value you want, this shows how far away the object will move from the camera. This will successfully place an object in front of the player, wherever they are looking at.
> 1 votes

# Answer
Why not simulate another click? since you already have mouse-click ray-casting (I assume), apply some random length to the ray. Any click will be in view, so your problem is already solved.
> 0 votes

---
Tags: three.js
---


# Question
Title: How to generate or smooth really large procedural terrain?
I'm currently trying to generate a really large procedural terrain in WebGL. I use a quadtree for LOD and plan to generate 1 heightmap for each quadtree node (terrain patch).

The heightmaps are generated on the GPU and with such a large terrain, 32 bits floats don't have enough precision for the smaller terrain patches. This results in terrain becoming "blocky". This article uses bicubic surfaces to smooth things out.

I thought a lot about it and the only other solution I have is to generate the smallest terrain patche on the CPU (with double precision) instead of the GPU, but continue to generate the larger patches on the GPU. But this doesn't seem like the best thing to do. Does someone have an idea for a better solution?

Also, I can't use double precision on the GPU because I'm using WebGL, which doesn't support it.

Thanks a lot :)

# Answer
At the radius of the Earth, with the center at the origin, 32-bit floating point offers us about half-metre precision laterally, so that's not enough to position centimetre-level detail.

So, our first step is not working that far from the origin. I presume you're already breaking your terrain into chunks and positioning them close to the origin where the player/viewer is. The player's grand-scale position can be stored elsewhere with low precision and updated as we move from chunk to chunk, re-centering as we go. That gives us enough precision to place our vertices accurately.

Now we just need to *generate* those positions accurately, and we can do this by applying the same chunking logic internally too — separating where the chunk is in the grand scheme of the whole planet from the working space numbers we use for our local detail.

Let's say you're using something like a Perlin noise function in your generator. This will generally involve doing something like...

1. Flooring/rounding the input position to an integer lattice
2. Computing a relative position within that lattice
3. Using the integer lattice to sample pseudo-random values / gradients at the closest corner points
4. Using the relative position to blend between these random values

We can see we have:

* a component that needs global information (where we are in the planet) at low precision (integers)
* a component that needs only local information (where we are within this lattice cell) at high precision

We can separate these two early in our generation process, rather than at the last moment inside the noise function itself. Then pass the pre-separated high & low-precision values down into our noise functions to get high-precision outputs, even for chunks that are logically much too far from the origin to have such precision.

When we're ready to generate a new chunk of terrain, we calculate the global lattice coordinates of a master point in our patch (say, the bottom-left corner, or the center), and the relative offsets of each of the four corners from that master point.

Those relative offsets may still suffer some rounding, depending on how you calculate them, but if we structure our calculation right it will be the same rounding when we calculate it from either side of the chunk seam, so that adjacent chunks will agree and show a perfectly welded join.

Now our local offsets are in a controlled range (say, tenths to hundreds, depending on the granularity of our base-level lattice unit), and we can interpolate between them to get the intermediate points with much higher precision. That then gives us high-precision position inputs to pass to our noise sampling functions.
> 3 votes

---
Tags: opengl, webgl, terrain-rendering
---


title: Make Unity GUI for mobile phones only?

text:
# Question
Title: Make Unity GUI for mobile phones only?
I'm using Unity and I want to make a responsive GUI for portrait resolution only. Now I'd like to know if this is a good or bad idea when I force the user to play my game in portrait mode only. Shall I use autorotate? The problem is that when you use landscape mode my GUI looks really shitty.

I have some background images and I'd like to know if I should save them for the highest resolution available in mobile devices (like tablets)? Or shall I ditch the tablets and develop the GUI with the background images for mobile phones only? TIA

# Answer
It sounds like you are doing something wrong when you design your UI. Supporting only portrait, or only landscape, is not a bad thing, but supporting both is better. If you decide that your game will only support portrait mode, that's fine.

However, in the case you want to support multiple resolutions, portrait/landscape, wide screens or CRT boxes, here are some tips:

* UI elements can have a "variable" size that depends on the screen, using anchors. You can for example specify a button that its width is half of the screen's width. This means that regardless if you play on portrait or landscape, your button will resize itself to half the screen's width. This is one way to make buttons be more interactive, but it's not ideal for all cases.
* Using the above tip, you can also tick "keep aspect ratio" on images, so that they resize to the specified width/height, but the displayed image keeps it's aspect ratio. This is more likely to be used on image buttons.
* When positioning elements on the screen, do not use absolute pixels because it works on your editor. Instead, use screen portions. You want a button to animate itself and move to the middle of the screen? Then move it to `Screen.width/2`, `Screen.height/2` (or `0.5, 0.5` if using anchors).
* Another idea which I've used on an android project in the past, is to make a different layout of your UI for portrait and landscape. Simply make a check if `Screen.width` is bigger than `Screen.height`. Having different layouts makes your game look more professional.

I hope this helps you move to the right direction. For more information, you can read Unity's tutorials: Designing UI for Multiple Resolutions and Basic Layout.
> 3 votes

---
Tags: unity, android, game-design, gui, mobile
---


# Question
Title: How can I tell in code if vsync is disabled on desktop PC?
My game needs to behave differently to get the best performance if the user disables vsync globally (basically, I need to change the scheduling on my housekeeping operations).

Is there a graphics card independent way (SDK call, C/C++) for me to find out if vsync is disabled?

I'm using opengl/glfw 3.2.1, and I can use glfwSwapInterval(0) to force vsync disabling, but that's not the same as reading the player's current default preferences.

I can always use application settings, but it'd be good if the game could default to the most suitable approach for the default video settings.

# Answer
> 2 votes
I couldn't locate anything directly in GLFW that for checking the status of vsync.

According to the official OpenGL spec on swap intervals, swap interval access is provided via platform-specific extensions. You can query the swap interval as follows:

* On Windows, use `wglGetSwapIntervalEXT()`
* On Linux, use `glXSwapIntervalEXT()`

Note in the Linux case, no parameter is passed; if a value is passed, the call will attempt to set the swap interval rather than read it.

Also note, some GL drivers support adaptive vsync - I'm not sure how (if at all) this may factor into your problem, but it's something to be aware of.

---
Tags: opengl, glfw, vsync, win32
---


title: Enemy doesn't fire at player

text:
# Question
Title: Enemy doesn't fire at player
My script looks pretty good but it says `Target` variable has not been assigned value.

```
public GameObject AntagonisticElement;
public GameObject Target;
public float bulletSpeed;
public float enemySpeed;
public float bulletDestroyTime;
public GameObject explsn;
public GameObject bulletPrefab;
public Transform bulletSpawn;

Vector3 pos;

public float min = 20;
public float max = 10;

public int MaxCounter;
public int CounterStatus;
int numberofEnemy;
// Use this for initialization

void Start()
{

}

// Update is called once per frame
void Update()
{
    if (CounterStatus <= 0)
    {
        if (numberofEnemy < 3)
        {
            Vector3 creationPoint = transform.position;
            creationPoint.y = -0.5f;
            Instantiate(AntagonisticElement, creationPoint, transform.rotation);

            CounterStatus = MaxCounter;
            numberofEnemy++;
        }
    }

    else
    {
        CounterStatus--;
    }

    transform.LookAt(Target.transform.position);

    if (Vector3.Distance(transform.position, Target.transform.position) >= min)
    {
        transform.position += transform.forward * 4 * Time.deltaTime;

    }
    if (Vector3.Distance(transform.position, Target.transform.position) <= max)
    {
        shootAt();
    }

}

    void shootAt()
    {

        Instantiate(explsn, bulletSpawn.position, bulletSpawn.transform.rotation);
        var bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
        bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * bulletSpeed;

    }

```

# Answer
Although I can't be completely sure without seeing your script in the inspector, have you made sure to drag and drop a GameObject into the Target slot in your inspector?

If you want to do this in the script you could also find it by reference with:

```
void Start () {
     Target = GameObject.FindGameObjectsWithTag("Target");
 }

```
> 1 votes

---
Tags: unity, c#
---


# Question
Title: How can I detect touch intensity or pressure via libGDX?
How can I detect the intensity of touch pressure in libGDX? For example, low pressure, medium, medium-high, high and so on. There are some questions about it but there aren't answers for libGDX.

# Answer
> 1 votes
you can call

```
Gdx.input.getPressure()

```

This has been implemented in LibGDX here in July 2018 https://github.com/libgdx/libgdx/issues/5241

# Answer
> 2 votes
There's currently (update **1.9.6**) no way to get the touch pressure internally from within LibGDX but using callbacks from the android `MotionEvent` we can access the touch pressure anyways.

The code might look something like this:

```
// Inside your AndroidLauncher's onCreate method
final AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
final MainClass game = new MainClass();
final View view = initializeForView(game, config);
view.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(final View v, final MotionEvent event) {
        // The easiest option would probably be to have a
        // (static?) variable in 'game' that stores pressure.
        game.pressure = event.getPressure();
        return false;
    }
});

```

This will register an `OnTouchListener` that will update the `pressure` variable each time the screen is touched. You can then use this `pressure` variable in your code after a touch event has happened to query the touch pressure.

This is the method I've used the (few) times I've needed touch pressure in LibGDX games and it seems to work more or less flawlessly.

---
Tags: libgdx
---


# Question
Title: Which part of the frustum sits at the eye position?
In Java I create a frustum projection matrix via

```
Matrix.frustumM(projMatrix, 0, left, right, bottom top, near, far);

```

and a view matrix via

```
Matrix.setLookAtM(viewMatrix, 0,
                               0, 0, -2.5,  // eye position
                               0, 0, 0      // look position
                               0, -1, 0);   // up direction

```

My question is:

Which part of the frustum originates at the eye position? Is it the tip of the pyramid, or the centre of the near plane?

# Answer
> 0 votes
The eye position is at the tip of the pyramid though the actual projection will end up on the near plane i.e the near plane will be your "screen"

---
Tags: opengl, java, android, opengl-es2
---


# Question
Title: Help finding coordinate for left of screen in this frustum
I have a frustum with `l=-2`, `r=2`, `n=0.5`, `f=10`, corresponding to left, right, near, far respectively. I also define top and bottom too.

I've set the camera eye up at `(0, 0, -2.5)`, looking directly at `(0, 0, 0)` with up `(0, 1, 0)`.

Suppose I want to position an object centred at `z=-1`. I want to find the `x` coordinate so that under this frustum it appears exactly centred on the left edge of the screen.

I set up the following diagram to help me:

```
                       +z
                       |
            \          |          /
     -x<_____\_________|_________/______>x
              \____x___|-1      /
               \       |       /
                \      |      /
                 \_|l|_|     /
                  \    |    /     |near dist=n=0.5
                   \   |   /      |
                    \  |  /       |
                     \a| /        |
                      \|/         |
                       |-2.5
                       |
                       -z

```

So to find `x` I can use simple trig. Since `tan a = |l|/n` and `tan a=x/1.5` then the formula for `x` is `x=|l|/n*1.5=2/0.5*1.5=6`, where `|.|` is the absolute value.

But when I use this `x` value to draw an object left of the centre, it does not appear centred at the edge of the screen. I can see the object but it's not on the edge. Moreover, if I increase `n` then the gap between the object and the left edge increases. What am I doing wrong?

**UPDATE**

Empirically I have discovered that if I compute `x=|l|/n*2.5` then my object is correctly centred on the left edge of the device screen, and works for any `n` value I choose. Not sure why 2.5 works...

**SOLUTION**

Not really worthy of an answer, but I found in some legacy code that the renderer was set up to transalte the z forward by 1 unit, so this was undoing my `-1` z value, hence why multiplying by 2.5 worked and not 1.5.

Despite this annoying fact, I'm now confident I fully understand how the frustum fits into OpenGL.

# Answer
> 0 votes
In your example:

```
0.5*left / n = x / 1.5
-1 / 0.5 = x / 1.5
-2 = x / 1.5
-3 = x

```

Or more elaborately, if you want to go via the angle it self:

```
tan( a ) = 0.5*left / 0.5
a = atan( -2 )
tan( a ) = x / 1.5
tan( atan( -2 ) ) = x / 1.5
-2 = x / 1.5
-3 = x

```

---
Tags: opengl
---


# Question
Title: Keep platformer jump height consistent with different frame rates
I want to achieve a platformer jump similar to that of Super Mario Bros. (keep pressed the jump button to jump higher) and I want it to be frame rate independent. At 30 FPS it works as I want. However, I noticed that, if frame rate is lower (e.g. 10 FPS) the jump height is much lower.

The following is the pseudo-code I am using on my character. What am I doing wrong? Note: I'm considering the Y-axis to grow downwards, so a negative vertical speed means the character is moving upwards.

```
jump_force = 4000;
jump_max_speed = 800;
gravity = 2000;

yspeed = 0; // vertical speed (negative is upwards)
is_jumping = false;

update() { // called every frame
    dy = 0; // delta y-position for this frame

    if (yspeed != 0 && is_grounded()) {
        yspeed = 0;
    }

    if (jump_button_pressed() && is_grounded())
        is_jumping = true;
    else if (is_jumping && !jump_button_pressed())
        is_jumping = false;

    if (is_jumping) {
        yspeed -= jump_force * dt(); // dt() is delta time, i.e. time elapsed since last frame
        // cap vertical speed to limit jump height
        if (yspeed < -jump_max_speed) {
            is_jumping = false;
            yspeed = -jump_max_speed;
        }
    }
    else if (!is_grounded()) {
        // apply gravity only when the character is not jumping
        yspeed += gravity * dt();
    }

    dy = yspeed * dt();

    // if character would fall inside terrain, place it just above it
    if (dy > 0 && check_for_ground(x, y + dy)) {
        y = ground.y;
        yspeed = 0;
    }
    else
        y += dy;
}

```

# Answer
You need to decouple the render frequency from the simulation frequency: You measure the delayed time, do an appropriate amount of simulation steps, then render the frame.

The easiest way to do this, is to set the simulation frequency really high. For a platformer this should be easily achievable. I suggest 240Hz or 480Hz.

Then count the number of simulation frames that have passed during your game loop, and perform those.

Let's say your sim rate is 240Hz.

If your FPS is 120, then you do two simulation steps. On a 20 FPS machine, you need to do 12 of them.

If you cannot afford a high simulation rate, people often interpolate or extrapolate based on "left-over time."

This is the seminal article on this: Fix your timestep.

But personally, I use the high sim rate approach.
> 2 votes

# Answer
I noticed something similar with my particle simulation program. I was doing the same as you, only accounting for `delta time * speed_per_second` and changing the FPS changed the position of the particles. At high FPS they would overshoot. At low FPS they moved short distances. This is because the integration math is incorrect. We need acceleration too.

In order to have a more correct integration step, we must apply acceleration per delta as well as the velocity per delta.

```
double elapsed = dt();
speed += vector2(acceleration.x * elapsed, acceleration.y * elapsed);
pos   += vector2(speed.x * friction.x * elapsed , speed.y * friction.y * elapsed );

```

After I made these changes, the particles moved correctly. try that and see if it fixes your jumping problem
> 0 votes

---
Tags: 2d, platformer, frame-rate, jumping
---


title: How is raycasting implemented

text:
# Question
Title: How is raycasting implemented
I know what it's used for, I know what it does.

What I am essentially asking is what is the math/code behind how it works?

I'm aware that any custom implementation would likely be slower than an engines official implementation, I just am interested in how it works.

# Answer
I assume you're refering to how a game like Wolfenstein 3D uses raycasting?

Here is a nice explanation on what raycasting is, and how it's implemented:
https://lodev.org/cgtutor/raycasting.html

Here is a summary of a raycasting implementation (taken from the above website, edited for clarity):

> The basic idea of raycasting is as follows: the map is a 2D square grid,
> and each square can either be 0 (no wall), or a positive value (some wall).
>
> For every x-position of the screen (every vertical strip of the screen),
> send out a ray that starts at the player location and points in the player's looking direction.
> Let this ray move forward on the 2D map until it hits a map square that contains a wall.
> If it collided with a wall, calculate the distance of the collision to the player, and use this distance to
> calculate how high this wall has to be drawn on the screen. The further away the wall is,
> the smaller it's on screen; the closer it is, the higher it appears to be.
>
> To find the first wall that a ray encounters on its way, start at the player's position, and each frame
> check whether or not the ray collided with a wall. If it is colliding, then the loop can stop.
> Calculate the distance, and draw the wall. If the ray position is not colliding with a wall, you have to trace it further. To do this, add a constant value to its position in the ray's direction. For this new position, check again if it's colliding with a wall or not. Keep doing this until a wall is hit.
> 1 votes

---
Tags: collision-detection, mathematics, raycasting
---


# Question
Title: Monogame - SpriteBatch.DrawString() won't work
Here is my `Game1.Draw()` method (Constants.HeroLayerDepth is equal to 1):

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.AntiqueWhite);

        //  gameEngine.DrawEverything(spriteBatch, camera);
        spriteBatch.Begin();

        spriteBatch.DrawString(defaultFont, "Test Field", new Vector2(0, 0),
            Color.Black, 0, new Vector2(0, 0), 0f, SpriteEffects.None, Constants.HeroLayerDepth);

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

Although I am calling DrawString(), I only see this after running the code:

How can I fix this?

# Answer
> 0 votes
```
spriteBatch.DrawString(defaultFont, "Test Field", new Vector2(0, 0),
        Color.Black, 0, new Vector2(0, 0), 1f, SpriteEffects.None, Constants.HeroLayerDepth);

```

The problem is the ‘scale’ parameter: it is set to zero in your code.

# Answer
> 0 votes
Sry, cant make comments. But is the `base.Draw(gameTime);` pheraps going to another overiding class that may make a `GraphicsDevice.Clear(Color.AntiqueWhite);`?

*(oh, this was an old question, guess you've moved along by now)*

---
Tags: c#, monogame, text
---


# Question
Title: AdMob interstitial ads not showing after publishing in playstore
I have create a Unity game, 1st I add an AdMob interstitial ads script on game object then try on my main camera when I test in my mobile before publishing. It has worked like real time ads and mistakenly clicked it and earn 0.3 so I create new ad unit placed it on my game then published my game. But the ads are not showing in real time. No error was found in AdMob but 147 ad requests are shown in AdMob and ads are not visible when my game 1st scene opens.

Here is my interstitial ads script code:

```
using UnityEngine;
using System.Collections;
using GoogleMobileAds.Api;

public class AdmobScript : MonoBehaviour
{
   private InterstitialAd interstitial;

   private void RequestInterstitial()
   {
      #if UNITY_ANDROID
         string adUnitId = "ca-app-pub-3129337025883034/9036322***";
      #elif UNITY_IPHONE
         string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
      #else
         string adUnitId = "unexpected_platform";
      #endif

      // Create an interstitial.
      this.interstitial = new InterstitialAd(adUnitId);
      // Load an interstitial ad.
      this.interstitial.LoadAd(this.CreateAdRequest());
   }

   // Returns an ad request
   private AdRequest CreateAdRequest()
   {
      return new AdRequest.Builder().Build();
   }

   private void ShowInterstitial()
   {
      if (interstitial.IsLoaded())
      {
         interstitial.Show();
      }
   }

   public void Start()
   {
      RequestInterstitial();
   }

   void Gameover()
   {
      if(interstitial.isloaded){
        ShowInterstitial();
      }
   }
}

```

# Answer
The ad need a Build request function. Execute the below code and run on the testing device. if you got test ads then surely it will open in play store version also. Then update the new build in play store.

```
private void RequestInterstitial()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-3129337025883034/9036322***";
#elif UNITY_IPHONE
     string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
#else
     string adUnitId = "unexpected_platform";
#endif

// Create an interstitial.
this.interstitial = new InterstitialAd(adUnitId);
 // Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.interstitial.LoadAd(request);
}

```

The ad calling method must be like this

```
private void GameOver()
{
  if (this.interstitial.IsLoaded()) {
    this.interstitial.Show();
  }else{
     RequestInterstial();
  }
}

```
> 0 votes

---
Tags: unity, c#, unity-ads
---


# Question
Title: Unity - Button still interactable even when interactable is set to false
my button can still be pressed in-game even if I set it to `button.interactable = false;`

What I'm trying to achieve is when the Panel `CropsPanel` is opened, or active in Unity, I want the `EquipmentButton` to be disabled and to be not usable by the user. Here is the code I've written:

```
 public void Start ()
     {
         GetComponent<Button>().interactable = false;
         if (CropsPanel.activeInHierarchy == true)
         {
           EquipmentButton.interactable = false;
         }
     }

```

I have also set all buttons in the inspector, placed a `Debug.Log("msg here");` to see if the particular code is working. But I can't seem to get it working. Am I missing something? Thanks guys!

# Answer
```
//using public you can directly drag a button from Hierarchy and drop it in inspector
public Button EquipmentButton;
void Start()
{
//You can link the button on runtime using this line.
  EquipmentButton = GameObject.Find("Button_Name_In_Hierarchy").GetComponent<Button>();
//Now disable it
  EquipmentButton.intractable = false;
}

```

initially CropsPanel is disable means don't declare it in start function. keep it in an update or create some other function to check it

```
void Update()
{
  if (CropsPanel.activeInHierarchy == true)
     {
       EquipmentButton.interactable = false;
     }
}

```
> 1 votes

---
Tags: unity, gui
---


# Question
Title: How to use JavaScript language in unity?
I recently read somewhere that the unity engine supports JavaScript language but I have a question.
How to use JavaScript language in unity engine?

# Answer
Your information is out of date. Unity used to support Javascript, via a custom Javascript variant language called UnityScript. It also used to have a language called Boo. Support for both has been discontinued. C# is now the only language that Unity uses for scripts. By default, this is 3.5 version of C#, but 4.6 is an option you can switch to via the Player Settings option screen.
> 4 votes

---
Tags: unity, javascript
---


title: How do I draw a rectangle in Pygame?

text:
# Question
Title: How do I draw a rectangle in Pygame?
I am getting the error "*AttributeError: 'Rect' object has no attribute 'draw'*" with this code:

```
import pygame
import sys

def terminate():
    pygame.quit()
    sys.exit()

pygame.init()

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
fps=30

screen_height = 520
screen_width = 650
screen = pygame.display.set_mode((screen_width,screen_height))

class Rect(pygame.sprite.Sprite):
    def __init__(self,width,height,color,value):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.value = value
    def change_value(self,color,value):
        self.image.fill(color)
        self.value=value

rects = pygame.sprite.Group()

rect = Rect(100,100,black,1)
rects.add(rect)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            terminate()

    screen.fill(white)
    rect.draw(screen)

    pygame.display.flip()

    clock.tick(fps)

```

Why is this? How do I render a rectangle?

I am trying to render and save 8 rectangles which are clickable to turn them on or off. I am trying to render the rects as objects to later use their collision for mouse clicks.

# Answer
> 1 votes
As the error message says, the `Rect` object doesn't have a `draw` method. (Documentation for `Rect` is here, for reference.)

Perhaps you meant to write—

```
pygame.draw.rect(screen, black, rect, 1)

```

—if you just wanted a rectangle's edge lines like this:

Or maybe you meant—

```
screen.fill(black, rect)

```

—for a filled rectangle like this:

---
Tags: rendering, pygame
---


# Question
Title: How do I override a SteamVR Controller's transforms in Unity?
I'm trying to provide an illusion to the user by rotating the controller about an arbitrary axis in the LateUpdate() method. But this doesn't seem to be having any effect as the controller probably is constantly getting updated by its real world location. Is there any way to override its real world position and orientation with a transformation in script?

# Answer
> 0 votes
I'd recommend hiding the "real" controller object, and creating your own visible object that matches its movements plus an offset you control, something like this:

```
public class FollowWithATwist : MonoBehaviour {

    // Set this to point at your controller
    public Transform objectToFollow;

    // Set this to the twist you want to apply
    public Quaternion extraRotation;

    void LateUpdate() {
         transform.position = objectToFollow.position;

         // This applies the twist in the controller's local space.
         // Flip the multiplication order if you want it applied in world space.
         transform.rotation = objectToFollow.rotation * extraRotation;
    }
}

```

If you want the object to interact with physics, then do this in FixedUpdate by applying forces/torques to the rigidbody instead, to minimize teleportation artifacts. I have previous answers showing how to do this with velocity for translation and torque for rotation.

---
Tags: unity, virtual-reality, htc-vive, steam-vr
---


# Question
Title: 2d side scroller slope physics and collisions
In old 2d games such as double dragon, streets of rage etc. where the player could move “up and down” on the y-axis to give an illusion of depth (as opposed to something like Mario) how were slopes and stairs handled along different points on the y-axis to give the appearance of still moving in a straight line?

For instance in the above picture would you set collision masks where the green lines are? Then imagine the characters are the red and blue lines respectively, how would you handle them in effect being moved “down” by gravity when in fact there isn’t really any gravity? For the top line I assumed when it hit the green line, rather then stopping or bouncing back on the x-axis you’d just nudge them down and continue the x movement?

I understand how this could be completed in 3D but I’m perplexed how this would’ve been achieved in purely 2d environments. Or maybe I’m imagining slopes/stairs in these old games...

I’m working in SpriteKit, so any ideas specific to that would be great but just understanding how this was accomplished theoretically in the first instance would be great.

Thanks

edit - after some thinking I don't think my 'collision' theory would work going down the slope for the blue line as it wouldn't be colliding unless it came off it's "straight" path, and also the problem would be reversed when going 'up' the slope.

so for instance in the above image where the characters are moving up the slope the other way I'm curious how this would have been handled? My thoughts now are, would the darker grey area with the "1" on it, actually be an entire entity itself or a collision mask? You'd then work out based on the characters "Y entry" point on to it (either at the top or the bottom) and based on their direction, where their 'Y' point should then be?

# Answer
# It's really no different than sloped 2d case

Consider the following picure.

In this instance, to move over the ramp you would just move using the slope of the ramp. Easy right? y = mx+b kind of stuff.

Now look at this picture.

Notice anything different? Actually notice what really isn't different? The only thing we changed is that we extended this ramp out, but straight in one dimension.

So lets think about this, would anything change about how you moved if you started walking from the top right corner on end of the road to the top left corner of the other from the first picture to the second?

No, it's as if there wasn't an "extension into 3D" at all, you move the character by the same slope and same amounts as you would have in the first picture.

But what about if you moved down a bit?

Notice how the slope you have to move and by how much you have to move by while on the ramp does not change, and the x position where you encounter the ramp doesn't change either. So what does change? *The only thing that changes is your Y position, everything else is the same*.

Notice that this is the **exact same scenario as the first case except the Y has changed**.

Now how might one implement such a feature? There's a bunch of ways, but one way might be to assign a slope value to each tile, or something along those lines. On most tiles, your slope would be 1 x over 1 y, or 1, so your character will just move horizontally, but when it slopes, it might be 1/2, so when your character moves, x moves + 1/2 and Y moves 1/(1/2) or 2 units. If you aren't supposed to move in an area (ie to an area which may be below the ram) you could just block movement to those areas via what ever collision you have in your game.

I have no clue if you are using tiles or are just rendering objects or something else. If rendering objects you can just assign the slope to the object. You can use collision checks with the bottom of your character and the sloped object to figure out the slope you should be using.
> 2 votes

---
Tags: 2d, collision-detection, physics, collision-resolution, side-scroller
---


# Question
Title: Drawing each sprite at different location
I can draw multiple sprites but they are all on top of each other at (0,0). How would I make each sprite appear after one another in a row?

My Rect class and Draw function:

```
class Rect(pygame.sprite.Sprite):
    def __init__(self,color,width,height,value=0):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.value = value
        self.x = 0
        self.y = 0
    def change_value(self,color,value):
        self.image.fill(color)
        self.value=value

def DrawRects():
    rect1 = Rect(red, boxW, boxH)
    rect2 = Rect(black, boxW, boxH)
    rects.add(rect1, rect2)

    rects.draw(screen)

```

# Answer
I solved the question. Rewrite the attributes to the Rect() class constructor. Use a method to receive arguments of desired starting x,y of where to start rendering sprites at.

```
class DrawableRect(pygame.sprite.Sprite):
    def __init__(self,color,width,height,value=0):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.value = value
        self.x = 0
        self.y = 0
    def change_value(self,color,value):
        self.image.fill(color)
        self.value=value

def DrawRects(start_x, start_y, rect_spacing, red):
    current_x_pos = start_x
    for rect_num in range(0,8):
        rect = DrawableRect(colour_list[rect_num], boxW, boxH)
        rect.rect.x = current_x_pos
        rect.rect.y = start_y
        current_x_pos = current_x_pos + rect.rect.width + rect_spacing
        rects.add(rect)
    rects.draw(screen)

```

In main loop:

`DrawRects(screen_width*0.01, screen_height*0.1,10,red)`
> 1 votes

---
Tags: pygame
---


# Question
Title: Is it ok to return a call to itself inside a method that has a return type?
Hello all I am making a little blackjack game in Unity. Although these classes don't actually use Monobehaviour or anything just yet.

I have this method and I'm not sure it will work like this or not. I need a way for it to return the card, but if the card has already been dealt out it needs to just repeat until it finds a card that isn't already dealt to return to the original place where i invoke this method from.

```
    public Card TakeRandomCardFromDeck()
{
    var rand = new Random();
    int randomIndex = rand.Next(cards.Length);
    Card card = cards[randomIndex];
    if (card.stillInDeck)
    {
        cards[randomIndex].stillInDeck = false;
        return card;
    }
    else
    {
        return TakeRandomCardFromDeck();
    }
}

```

Im specifically worried about the else{ ....... part.

NOTE: I have already done this and whilst it seems to work, its hard to tell whether its actually ran into a card that is already dealt yet since I only have a few cards dealt so far. (I've ran it dozens of times and not had any errors in the one test deal it performs on each run)

# Answer
> 3 votes
Yes, this is OK (when done with care).

The technique of using code that calls itself is called "recursion," and a method that does this is called a "recursive" method.

Many of the early definitions of what we now think of as programs and even computation itself were based on recursion, and it's essential to algorithm design paradigms like divide & conquer (see classics like QuickSort).

The trick is that this inner call is itself a function call — so it involves adding extra data onto your program's stack to track the variables of the call-within-the-call. And another for the call-within-that-call-within-the-call, and so on... (outside of special cases like tail recursion where a suitable compiler might be able to optimize it into iteration instead)

So that means your stack grows telescopically until it hits a "base case" where your function can return a value without calling itself yet again. Then the stack telescopes back, resolving each call from the inside out until the original call finally returns.

If a base case isn't guaranteed to be reached in a "reasonable" number of iterations, this can cause what's called a "Stack Overflow": your environment runs out of allocated space to keep growing the stack, and computation will terminate with an error.

In the case you've shown, as long as we have at least one card left in the deck, we're unlikely to keep repeating *too* long... but it is technically possible.

In this case though, we can make a non-recursive method that always solves the problem in a single pass, using a Fisher-Yates shuffle (also called a Knuth shuffle):

```
Card[] deck;
int cardsLeftInDeck;

public Card Draw() {
    if(cardsLeftInDeck == 0) {
        // Here you could return the "No Card"
        // or just reshuffle the discards
        // and proceed from a fresh deck like so:
        cardsLeftInDeck = deck.Length;
    }

   // Choose a random card from the remaining deck.
   int drawnIndex = Random.Range(0, cardsLeftInDeck);
   Card drawnCard = deck[drawnIndex];

   // Swap the card to the end of the remaining deck.
   // (The high indices become our discard pile)
   cardsLeftInDeck--;
   deck[drawnIndex] = deck[cardsLeftInDeck]
   deck[cardsLeftInDeck] = drawnCard;

   return drawnCard;
}

```

This always gives you a valid random card in a single try, guaranteed.

---
Tags: c#
---


# Question
Title: UNITY || How to access the "exit transitions" of the current played clip from the animator?
So, I have an animator , i can access it. But from there I have no idea how to access the clips inside. I need to access the transition of the clips.

I got as far as accessing the object of the "Animator" class.

EDIT:

It appears The TransitionInfo datatype doesnt provide conditions. I need the conditions!

# Answer
It's somewhat complicated but achievable. This is a list of things you'll need to go through:

1. Give the transition a name in the editor. Let's say you call it `"AnimAToAnimB"`.
2. Figure out which layer of the animator the transition is in. Let's assume it's in the default `"Base Layer"`.
3. Query the hash code of the transition up-front via code:

`animator.StringToHash("Base Layer.AnimAToAnimB");`

and store it in some variable, let's say `transitionAToBHash`.
4. Research "Animator State Machine Behaviours". You'll want one attached inside the layer of the transition that you're interested in.
5. Implement your own custom StateMachineBehaviour that will be able to listen and receive animator state change callbacks. More info: https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
6. Once you have your custom state behaviour attached and implemented, upon receiving the OnStateExit callback, grab the currently active animation transition and compare it to your cached transition hash:

---

```
// inside your custom state machine behaviour

override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
   var transitionInfo = animator.GetAnimatorTransitionInfo(layerIdOfYourTransitionAToB);

   if (transitionInfo.userNameHash == transitionAToBHash)
   {
      // PROFIT! your transition "transitionAToB" has just started!
   }
}

```

Note: it can get a lot more complicated if you're using things like sub state machines.
> 2 votes

# Answer
Use the below code to call the animation using script

```
public Animator Anim;
void Start(){
    Anim.Play("Animation_Clip_Name");
}
//Trigger it by button click or inside other functions to change the animation.
public void NextAnimation()
{
   Anim.Play("Next_Animation_Name");
}

```
> -1 votes

---
Tags: unity, c#, animation, scripting, animator
---


# Question
Title: How to stop and start sprite sheet flipbook materials in a widget blueprint?
I have a flipbook material I created from a sprite sheet to add some fireworks to a game I'm working on. I have the material set up and it is showing the animation of the firework like it should. However the animation in the material always repeats forever in a loop. I added an image to a widget to display the flipbook animation in a widget blueprint. The animation is shown in the blueprint as expected. The problem I have is getting the animation to start only when I show the animation. Being that the animation in the flipbook material is always looping, every time I show the image to show the firework, it seems to always start in a random frame, rarely is that frame actually the first frame. I read that I can control the speed of the animation in the flipbook. How can I stop the flipbook animation from looping indefinitely and only start the animation once I show the widget containing the image used to show the flipbook animation?

# Answer
> 2 votes
Add a Time node and Multiply node. Take the Time node and pass it as an input to the Multiply, add a float parameter as the other input on the multiply node then plug the output of the multiply into your AnimationPhase input on the flipbook node (the top input). Now at runtime you can set the float parameter to 0 to stop the animation, or 1 to play it (or 2 to play at double speed etc)

---
Tags: animation, sprites, unreal-4, materials, blueprints
---


# Question
Title: Python: I have a python statement which should work but it doesn't
The error in the picture is highlighted in red.

So, I have used this code on another computer and it worked, why wont it work now? I may have made a really small and stupid error and if I have I'm sorry for wasting your time but, it should work. By the way, this is only made to run in the python shell and it is not supposed to have an graphics except for the text.

For a bit of context, this is being used at the beginning of a game I am creating and it is used to determine the difficulty level.

If this isn't supposed to work at all but there is an alternative, I would appreciate the help.

All help, comments and answers are appreciated.

# Answer
> 1 votes
You need to write `while difficulty < 1 and difficulty > 3`. A comparision needs two elements, and the second statement is currently missing the left hand side operand. Note that the statement does not ever evaluate to true, since an integer cannot be smaller than one and larger than three at the same time. You probably meant to use `or` here.

---
Tags: python
---