# Question
Title: How do I get a Metal texture ID to render to it with Ogre?
I looked in the documentation, but I don't know how to get the texture ID.

```
void* texPtr = SixDegreesSDK_GetBackgroundTexture();
            if (texPtr != nil) {
                id<MTLTexture> mtlTexture = (__bridge id<MTLTexture>)texPtr;

                id<MTLDevice> device = [mtlTexture device];
                // !!! Not fond of creating a new command queue for every texture
                id<MTLCommandQueue> commandQueue = [device newCommandQueue];
                id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
                id<MTLBlitCommandEncoder> blitEncoder = [commandBuffer blitCommandEncoder];

                NSUInteger textureWidth = mtlTexture.width;
                NSUInteger textureHeight = mtlTexture.height;
                NSUInteger rowbytes = mtlTexture.bufferBytesPerRow;
                MTLPixelFormat  pixFormat = mtlTexture.pixelFormat;
                CVPixelBufferRef _CVPixelBuffer = NULL;
                NSDictionary* cvBufferProperties = @{
                                                     (__bridge NSString*)kCVPixelBufferOpenGLCompatibilityKey : @YES,
                                                     (__bridge NSString*)kCVPixelBufferMetalCompatibilityKey : @YES,
                                                     };
                CVReturn cvret = CVPixelBufferCreate(kCFAllocatorDefault,
                                                     textureWidth, textureHeight,
                                                     kCVPixelFormatType_32RGBA,
                                                     (__bridge CFDictionaryRef)cvBufferProperties,
                                                     &_CVPixelBuffer);
                const IOSurfaceRef surface  = CVPixelBufferGetIOSurface(_CVPixelBuffer);             // available in ios11 sdk, ios4 runtime

                MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixFormat
                                                                                width:textureWidth
                                                                                height:textureHeight
                                                                                mipmapped:NO];
                id<MTLTexture> metalTexture = [device newTextureWithDescriptor:textureDescriptor
                                                                          ioSurface:surface
                                                                              plane:0];

                MTLRegion region = MTLRegionMake2D(0, 0, textureWidth, textureHeight);

                [blitEncoder copyFromTexture:mtlTexture
                                 sourceSlice:0
                                 sourceLevel:0
                                sourceOrigin:region.origin
                                  sourceSize:region.size
                                   toTexture:metalTexture
                            destinationSlice:0
                            destinationLevel:0
                           destinationOrigin:region.origin];

                [blitEncoder endEncoding];
                [commandBuffer commit];
                [self.mEAGLContext texImageIOSurface:surface target:GL_TEXTURE_2D internalFormat:GL_RGBA width:textureWidth height:textureHeight format:GL_RGBA type:GL_UNSIGNED_BYTE plane:0];

```

# Answer
Ogre does not support Metal at this time. `MTLTexture` does not have any concept of a texture ID. If one library is returning a `MTLTexture` and the other expects an OpenGL texture ID, you'll need to copy the `MTLTexture` into an OpenGL texture created using `IOSurface`s.

The documentation on `IOSurfaces` is a bit slim, unfortunately. Once you have an `IOSurface`, you can blit the `MTLTexture` into it using a `MTLBlitCommandEncoder`. You can then retrieve an OpenGL texture from the `IOSurface` via `CGLTexImageIOSurface2D()`.

It might look something like this (not actually compiled, probably needs cleaning up):

```
NSDictionary* properties = @{
    IOSurfacePropertyKeyWidth : [NSNumber numberWithInt:textureWidth],
    IOSurfacePropertyKeyHeight : [NSNumber numberWithInt:textureHeight],
    IOSurfacePropertyKeyRowBytes : [NSNumber numberWithInt:rowbytes],
    IOSurfacePropertyKeyPixelFormat : [NSNumber numberWithInt:pixFormat],
    // ... etc. with any other relevant properties
};
IOSurface* ioSurface = [[IOSurface alloc] initWithProperties:properties];

```

Next you can get a `MTLTexture` from the `IOSurface` by doing this:

```
MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixFormat
                                                                                width:textureWidth
                                                                                height:textureHeight
                                                                                mipmapped:NO];
id<MTLTexture> metalTexture = [metalDevice newTextureWithDescriptor:textureDescriptor
                                                          ioSurface:ioSurface
                                                              plane:0];

```

Now, I've never personally used a `MTLBlitEncoder`, so I don't know the gory details, but it looks like once you've created one, you can call `-[MTLBlitCommandEncoder copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:]`. I believe once that blit command has been completed, the `IOSurface` will contain the texture data. Apple has some sample code showing how to use them.

From there you can do:

```
GLint glTextureID = CGTexImageIOSurface2D(glContext, GL_TEXTURE_RECTANGLE_ARB, GL_RGBA, textureWidth, textureHeight, GL_BRGA, GL_UNSIGNED_INT_8_8_8_8_REV, ioSurface, 0);

```

(That assumes you want an 8-bit per channel RGBA texture and that the `MTLTexture` was in that format.)

Here's some additional sample code for sharing between Metal and OpenGL.
> 1 votes

---
Tags: ios, metal
---


# Question
Title: How to add collision to this script in Unity
I Want to be able to have collision were my player can't go through objects with colliders un Unity but I don't know how to make that happen, can you please help?

```
public float moveSpeed;
    private Rigidbody2D RB;
    Vector2 movementDirection;
    Vector2 moveVelocity;

    private float inputX;
    private float inputY;

    // Use this for initialization
    void Start ()
    {
        RB = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame (Good place for Input so we can check on every frame)
    void Update()
    {
        // Gather the Input of the X and Y axis and put it into the assigned variables
        inputX = Input.GetAxisRaw("Horizontal");
        inputY = Input.GetAxisRaw("Vertical");
        // Take the numbers from both the X and Y axis and combine it into a Vector2 called "movementDirection"
        movementDirection = new Vector2(inputX, inputY);
        // Normalize moveDirection and add moveSpeed to get the final result of where the player needs to go
        moveVelocity = movementDirection.normalized * moveSpeed;
    }

    // FixedUpdate is called between every frame and every 2 frames to try to account for different computer speeds (Good for applying force so that gravity and so on isin't as affected by PC prossessing power)
    void FixedUpdate ()
    {
        // Take the current position and apply the final result/moveVelocity variable then multiply it my Time.fixedDeltaTime (We use "fixedDeltaTime" because it is good practice to do this in the "FixedUpdate" Function)
        RB.MovePosition (RB.position + moveVelocity * Time.fixedDeltaTime);
    }

```

# Answer
> 0 votes
It is usually done by using the Add Component button as someone in the comments said, but what I think that you asked (although you are not very clear) is that you want to add it via script

In you start method, you need to add this code:

```
gameObject.AddComponent(typeof(BoxCollider2D));

```

This way, you can add any other collider by just changing the type over there in that line of code.

Hope this helps!

# Answer
> 0 votes
Colliders are a type of Component that you would tipically attach to your GameObjects in Unity's Inspector window, by selecting one in your scene and choosing one from the list;

However, if for some reason you need to add a component to an object at runtime, you can use the `GameObject.AddComponent<T>()`.

There are multiple collider types you can choose from (some also have a 2D counterpart)

* `BoxCollider`
* `MeshCollider`
* `SphereCollider`
* Etc...

If you want to add a `BoxCollider` component to your GameObject you would do:

```
YourObject.AddComponent<BoxCollider>();

```

`YourObject` is the name of the GameObject you are attaching the component to. If it's on the current instance, `this` can also be used

# Answer
> 0 votes
Collision detection in Unity has a few non-obvious pitfalls.

First of all, check the collision action matrix at the end of the Unity Manual article on colliders. If you want your player-character to not fall through other objects, then:

* Your player and the object must have colliders in the right shape
* Neither collider must have the "is Trigger?" checkbox marked
* Your player-character must have a Rigidbody
* The object must either also have a Rigidbody or its colliders must have the "Static" checkbox marked (which means that this collider will not move during the game)

Another potential problem might be that you are mixing 2d colliders and 3d colliders. The 2d collision system and the 3d collision system are completely separated from each other. 2d colliders and 3d colliders do not interact with each other.

When you also verified this, then another possible pitfall is that they are on different physics layers which are not configured to interact with each other.

When collisions still don't work the way you expect them to do: How are you moving your player-character? Are you modifying its `transform.position` or are you using `Rigidbody.MovePosition`? If you do that, you aren't *moving* the character, you are *teleporting* it. If you try to teleport an object into or through a collider, the Unity physics engine will let you do that. For that reason you should always move an object by adding forces to its Rigidbody.

---
Tags: unity, c#, 2d, collider
---


# Question
Title: How Frustum Culling and Sky Box Working Together ? The skybox appears where it should not appear
When i did frustum culling, far parts of land not rendering. It is good like i want. But after I see sky box instead of these parts. My question is, is this normal ? Or what i need to see or what i need to do ? Because it doesn't look nice in the game.

I will show my problem to you with pictures. Over "Blender" program.

I ADDED NEW PICTURE:

# Answer
So before you added frustum culling, the far-terrain was showing, and now it is not? I assume you draw your terrain in chunks, and some chunks are culled? Are you using an existing engine, or writing your own?

It sounds like the far-plane of the culling frustum is set too close then.

Are you sure that your projection matrix and frustum cull use the same far-distance?

UPDATE based on your new illustration:

You can not afford to cull the orange marked chunks. You either:

1. Need to render them, and only cull behind camera, and out of the view cone.
2. Or add fog, so that terrain chunks that lie behind your far plane are not visible, because they are fully hidden by fog. In that case, you can keep culling them out as you do now.

Players can sometimes hate fog, so maybe it's best to go for option 1, which can be achieved by moving out your clipping far plane so that it is behind everything in your world.
> 2 votes

---
Tags: opengl, skybox, frustum-culling
---


title: Bullet 3D Physics Objects Not Rotating?

text:
# Question
Title: Bullet 3D Physics Objects Not Rotating?
So I've got Bullet 3D controlling the motion of objects rendered with DirectX. In the clipping below I've got 2 identical rectangles & 5 balls. The lowest rectangle has a mass of 0 and doesn't move (as expected). All other objects have a mass of 1 and fall as expected.

There are two issues that I'm seeing: 1. When the balls land on an angled surface (not shown) they don't rotate, but they do move 'down hill'. 2. Pictured below you see that the top rectangle is perched on the bottom rectangle when it should've rotated a bit and kept falling.

What do I need to do in Bullet to enable object rotations? I'm not a physicist so I suspect my google-fu is lacking, also the Bullet docs are painfully inadequate.

This code here is how I initialize my rigid bodies:

```
RESULT_CODE ubAddRigidBody(HANDLE collisionShape, float mass, ubVector3 position, ubVector4 orientation, HANDLE* rigidBodyHandle)
{
if (rigidBodyHandle == nullptr)
{
    return INVALID_PARAM;
}

if (_world->isValidCollisionShapeHandle(collisionShape) != SUCCESS)
{
    return INVALID_HANDLE;
}

auto transform = btTransform(btQuaternion(orientation.x, orientation.y, orientation.z, orientation.w), btVector3(position.x, position.y, position.z));
auto collisionShapeObject = _world->m_collisionShapes[collisionShape].get();

auto motionStateObject = new btDefaultMotionState();
motionStateObject->setWorldTransform(transform);

auto rigidBodyInfo = btRigidBody::btRigidBodyConstructionInfo(btScalar(mass), motionStateObject, collisionShapeObject);

// Enable rotations for the object

collisionShapeObject->calculateLocalInertia(mass, rigidBodyInfo.m_localInertia);
rigidBodyInfo.m_linearDamping = .2f;
rigidBodyInfo.m_angularDamping = .2f;

auto rigidBody = new btRigidBody(rigidBodyInfo);
auto uniqueHandle = _world->getUniqueHandle();

rigidBody->setFriction(.5f);
rigidBody->setRollingFriction(.5f);

_world->m_world->addRigidBody(rigidBody);
_world->m_rigidBodies[uniqueHandle] = unique_ptr<ubRigidBody>(new ubRigidBody(rigidBody, collisionShapeObject, motionStateObject));

*rigidBodyHandle = uniqueHandle;

return SUCCESS;
}

```

# Answer
Your problem is that you're not supplying an inertia vector in the `btRigidBodyConstructionInfo` constructor. Your rigid body dynamic spheres end up with a default inertia of `(0,0,0)`. This prevents angular motion, but not linear, so your objects slide but don't rotate. Look at some of the Bullet demo code and you'll see examples of the inertia being calculated for specific collision shapes, there are helper methods in the collision object or shape class.
> 3 votes

# Answer
you probably didn't calculateLocalInertia()

If I comment out that line here, the objects don't rotate:

```
btVector3 myStartingInertia(0, 0, 0);
instanceData[thisLocation].myDefaultMotionState = new
btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1),
btVector3(spawnLocation.x, spawnLocation.y, spawnLocation.z)));
myCollisionShape->calculateLocalInertia(myMass, myStartingInertia);
btRigidBody::btRigidBodyConstructionInfo myRigidBodyConstructionInfo(myMass,
instanceData[thisLocation].myDefaultMotionState, myCollisionShape,
myStartingInertia);
myRigidBodyConstructionInfo.m_restitution = 0.35;
myRigidBodyConstructionInfo.m_friction = 0.0;

```
> 0 votes

# Answer
I don't know about C++ clearly but when I use it in java the bullet library there is method called setToRotation you can check that
> -1 votes

---
Tags: c++, physics, bullet-physics
---


title: Transparency problem, phong model

text:
# Question
Title: Transparency problem, phong model
It's the first time I'm trying to implement the Phong lighting model. I'm pretty sure everything is working fine.

I was experimenting using different materials, meaning I played with Kd,Ks,Ka and Ns values when I came across this problem.

Whenever I use a material with alpha value less than one I get this weird result :

At first I thought it has to do with the normals of the model since they are all supposed to point away from the model but it doesn't seem to be the case.

Any ideas?

# Answer
This looks like what happens when you have depth writing enabled on a translucent material.

Sometimes a polygon in front (from our camera's perspective) renders first, and writes its depth into the depth buffer. Then when a polygon behind tries to render later, it detects there's already something at a closer depth and doesn't draw anything. That's where you get the faint/translucent parts.

Other times, one or more polygons further back draw first, then later the frontmost polygon draws on top of them. Stacking up multiple translucent polygons like this makes the result more opaque, leading to the darker regions in your image.

Since polygons are not depth-sorted by default, you end up falling into either of these two cases basically at random, leading to the patchy/inconsistent appearance you see here.

You can make this more consistent in a couple of ways:

1. Turn off depth writes. Then every front-facing polygon will be drawn, even if a closer polygon already got drawn there. This works for order independent blend modes like Add or Multiply. If your blending function is not order-indepent though (like Over/Layer/standard alpha blending), you'll still see inconsistent blending results where the order changes.
2. Sort your polygons — either front to back to render only the frontmost skin, or back to front to layer everything in the correct order. Note that not every possible arrangement of 3D polygons is sortable though.
3. Render your object fully opaque onto an off-screen buffer, then blend that buffer into your scene with translucent blending. This ensures you only see the frontmost surfacr, and get consistent blending everywhere.
> 1 votes

---
Tags: opengl
---


# Question
Title: How can I set the duration of a splash screen?
I am using Unity Pro, so I have all Splash Screen Tools available. I have a full screen image which I want to use as my splash screen. I want my splash screen to remain on the screen for n seconds. I want the splash screen to be cropped if it is not a perfect fit to the device's screen size.

The following settings give me the desired results, however the splash screen only stays up briefly, and does not allow me to choose the duration:

These settings allow for me to set the duration, however the splash screen is just an icon in the middle, and won't "Scale to fill (cropped)", like in the settings above:

I can use a blank image as my logo and add a background image, but it becomes all blurry. (The darkness goes away if as I change the overlay opacity.):

I have tried other variations in the settings, but the three attempts above are the closest I have come. I have tried removing the splash screen, and creating an empty Scene on launch with just the full-size cropped image, but this causes a delay to launch the app with a bad white flicker. I have tried using the static splash screen settings in addition to the blank starting scene, but this causes the screen to go black momentarily.

How can I use a full-screen cropped Splash Screen for a set duration?

# Answer
I don't have Unity Pro, but I've created my own "splash screen" in the past by just using Unity GUI. Then you have complete control.
> 2 votes

# Answer
The splash screen stays some minimum amount of time plus until the first scene is ready. Haven't tried it myself yet but what you can possibly do is -using the background image-, you can delay the load of the first scene by X seconds.

Here is the Unity manual link for splash screen:

https://docs.unity3d.com/Manual/class-PlayerSettingsSplashScreen.html

And the section related to your case:

> The entire duration of the Splash Screen is the total of all logos plus 0.5 seconds for fading out. This might be longer if the first Scene is not ready to play, in which case the Splash Screen shows only the background image or color and then fades out when the first Scene is ready to play.
> 1 votes

# Answer
You can use an alternative method, where you set the default time to the minimum value, and make the default splash screen reference a black screen. Then, at the start of the scene, use your default splash screen.
> 0 votes

# Answer
I don't have unity pro but I found this and thought that it would help:

https://docs.unity3d.com/Manual/class-PlayerSettingsSplashScreen.html
> 0 votes

---
Tags: unity, timing, splash-screen
---


title: Unity FPS style turning

text:
# Question
Title: Unity FPS style turning
I have this code:

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

public class Control : MonoBehaviour {

public int speed;
public Transform tf;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButton(1))
    {
        tf.eulerAngles = tf.eulerAngles + new Vector3 (0,
Input.GetAxis("Mouse X") * speed, 0);
    }
}
}

```

I would like to know how to use this so that when I move my mouse and hole right click the character will turn but the mouse will not move from the center of the screen

# Answer
> 1 votes
If you want to add mouse control to your game without having a cursor which might move off-screen, "capture" the mouse by calling `Cursor.lockState = CursorLockMode.Locked;`

This will make the cursor disappear and fix it to the center of the screen so you can implement classic FPS mouselook controls without having to worrying about what happens if the cursor moves offscreen.

To restore the normal mouse cursor behavior, use `Cursor.lockState = CursorLockMode.None`. You can also use `Cursor.lockState = CursorLockMode.Confined` which restores the mouse cursor but doesn't allow the player to move it out of the game window.

There are two things you need to keep in mind:

* It will only work if the game window is the currently active window. So you should keep setting it every `Update`.
* It won't work at all if you build your game for the WebGL platform. Web browsers do not allow websites to take control of the user's mouse cursor. If you wonder why, just imagine the kind of evil the advertisers could do with that.

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


# Question
Title: How can you tell if you are a large player on a large map or a small player on a small map?
If everything is scaled by a constant factor, can you tell that the world is smaller or larger?

I think you could look down at the ground and see that it's "closer".
But how do you know what should be the correct distance? What visual clues give it away?

**Edit:** The player controller has an **FPS** camera!

# Answer
The player can't.

The player can only estimate the size of objects on the screen by comparing them to other objects on the screen. When the player has no reference object where they can estimate the size from their real-world experience, then they can only guess what scale the world is in. They could be playing a character with the size of a flea or with the size of a giant. They won't be able to tell.

A good experiment in this regard is the genre of "rats maps", a popular theme for player-made maps in Counter Strike and other late-90s/early-2000s era first person shooters. In this mapping theme, the players feel as if they were shrunk to the size of rats while they play in a regular-scaled room. But actually the player-characters are still the regular size. What's scaled up is the world around them. Nevertheless, the illusion works pretty well. Why? Because the players recognize a lot of objects they know from real-life and see that they are about 20 times as large as they should be. So their brains tell them "with that many objects being 20 times larger than usual, the most logical explanation is that you and the other characters are shrunk to 1/20th of your normal size". <sub>which is actually unlikely because of how gravity works and because of the square/cube law, but our primitive monkey brains don't realize that :) </sub>
> 1 votes

# Answer
You can't tell if it's done correctly.

Take an FPS with 1-meter scale (people are 1 meter tall, etc). Everything looks good.

Now shrink everything by 90%. Everything will look the same.

This is of course barring weird things like making it SOOOO big that your character gets jittery as you move away from the center because of float rounding issues.
> 1 votes

# Answer
Normally, you can’t tell. One note however: In VR, your camera is controlled by the HMD the player is wearing, giving the player much more control over the view. If the world is scaled but the *translation* of movement from the real world HMD to the game world camera is not, then it will be quite apparent. For example, if the camera starts at the same scaled up height as the rest of the world, the player would appear to be floating in the air and would not be able to reach the floor, even if they were to lay on the ground in the real world.
> 1 votes

---
Tags: geometry, maps, scale, first-person-shooter
---


# Question
Title: How do I modify textures in SDL with direct pixel access?
I'm trying to use SDL\_LockTexture and SDL\_UnlockTexture for directly editing pixels in a texture. I'm using SDL 2.0. Setting the pixel value using the following code doesn't modify the texture:

```
void *pixels;
int pitch;

SDL_LockTexture(mytexture, NULL, &pixels, &pitch);

// Set pixel 100,100 to blue
((uint32_t *)pixels)[100 * 100] = 255;

SDL_UnlockTexture(mytexture);

```

# Answer
> 2 votes
Colouring SDL textures might be a little tricky. The following code should outline the main points of colouring a texture. The key is to fetch all required data from SDL before starting to alter the texture.

```
Uint32* pixels = nullptr;
int pitch = 0;
int format;

// Get the size of the texture.
int w, h;
SDL_QueryTexture(texture, &format, nullptr, &w, &h);

// Now let's make our "pixels" pointer point to the texture data.
if (SDL_LockTexture(texture, nullptr, (void**)&pixels, &pitch))
{
    // If the locking fails, you might want to handle it somehow. SDL_GetError(); or something here.
}

SDL_PixelFormat pixelFormat;
pixelFormat.format = format;
// Now you want to format the color to a correct format that SDL can use.
// Basically we convert our RGB color to a hex-like BGR color.
Uint32 color = SDL_MapRGB(&pixelFormat, R, G, B);

// Before setting the color, we need to know where we have to place it.
Uint32 pixelPosition = y * (pitch / sizeof(unsigned int)) + x;

// Now we can set the pixel(s) we want.
pixels[pixelPosition] = color;

// Also don't forget to unlock your texture once you're done.
SDL_UnlockTexture(texture);

```

Now, you should also note that modifying textures in code is *relatively* expensive. Also the code is not very clean, as editing C++ int pointer arrays and translating colours into different formats can cause problems, as what goes on where might not be as clear as needed. However doing this only when absolutely necessary shouldn't cause too much problems.

You also might want to consider using `SDL_SetRenderTarget` and modifying the texture by rendering to it. However for some tasks, rendering primitives to the texture might not be an option, and that's a case when modifying the pixels like this might be come handy.

# Answer
> -1 votes
incorrect- you need the "surface" format details from the texture- before one can blindly use MapRGB.

To get the data- you query the Texture- as outlined above.

MapRGB expects surface-\>format (in my case surface^.format) to be handed to it. check (SDL syntax in the header files)

Rendering to the texture is the SDL2 more efficient way. you generally batch render- dont update single pixels- (at least not until the next screen refresh). A lot of people OVER Render and realize it. Dont present until the screen (the monitor) is ready for it- doing so causes "flicker". Personally, Id wait until whatever is rendering to finish....then prepare the next batch of ops.

---
Tags: sdl, sdl2
---


# Question
Title: Does it make sense to export and use skeletal animation as sprites?
As tools like Dragonbones, Spine lets you export animations as both sprite atlas and skeleton data (JSON/binary), I'm not sure which format to use when importing to Unity.

I have few concerns:

* Will there be any differences between the quality of the animations, when imported as atlas vs skeleton data?
* Any other pros and cons, using one over the other?

If I use a sprite atlas, I don't have to depend on a third party runtime though. It is for mobile, so performance is also a concern.

# Answer
> 2 votes
The difference would probably be that while skeletal animations takes a little more performance than sprite animations it has some advantages. One being that the skeletal animation can run at any frame rate while the sprite animation can only run at the frame rate in which it is rendered. Another reason, depending on your animation system, is that you may be able to blend skeletal animations to create for example transitions.
The thing that happens when you export an animation as sprites is that you loose some information but foremost you loose the ability to modify the animations run time. But if you don't need to either of that I would recommend using sprites.

---
Tags: unity, 2d, sprites, skeletal-animation, spine
---


# Question
Title: Unreal Engine: Third person example project and multiplayer
I was fiddling around with multiplayer stuff in Unreal Engine. I looked into events that run only on server, multicasting events, replication of variables...

But there is something that I dont quite understand: When I load the Third Person example proyect, and enable more than one player, I can see the position and movements of the players being replicated on all clients.

While I understand that the position and the rotation of the players being replicated successfully (since the replication option is enabled in the pawn's blueprint option), I don't really understand why the animations are being replicated. I don't see any reference in the blueprint making animations replicated over the network.

Are pawn animations implicitly replicated on clients when replicating the actor's position? Am I missing some option/configuration I'm missing?

# Answer
> 1 votes
Character Movement Component is replicating a bunch of stuff for you by default and IIRC has some interpolating features built in, which is why the movement looks smooth even if you have simulated latency.

To my knowledge of the system, the animations aren't really replicated over the network. They are instead only played locally. Since position, rotation and velocity is replicated and interpolated, the animation states should be the same on both computers, creating the illusion that animations are replicated.

---
Tags: multiplayer, unreal-4
---


# Question
Title: 3D affine transformation (rotation) mimicking Mode 7, Java 2D
I watched videos of games using mode 7 like Outrun or Space Harrier and I want to make a game which imitates this classic graphic. I was inspired by Notch's Prelude Of The Chambered too.

After experimenting with pseudo 3D solutions from here StackOverflow and reading about 3D computer graphic I tried to make my own Mode 7 implementation with 3D affine transformations. (I've read here on stackoverflow too that using matrices and transformations is better than use pseudo 3d technics.)

A came up with this solution, but it doesn't work perfectly:

```
void mode7() {
    // width and height of texture
    int texW = 1024, texH = 1024;
    // ... of screen
    int screenW = 800, screenH = 800;

    // precalculated values
    int scrWH = (int) (screenW * screenH);
    int imgWH = (int) (texW * texH);

    // center of perspective projection -- the point I look at
    int toCenterOffsetX = screenW >> 1;
    int toCenterOffsetY = screenH >> 1;

    // depth
    float z = 1f;

    int textureIndex;
    int screenIndex;

    double tempX, tempY, tempZ;

    // screen coordinates
    double screenX, screenY, screenZ;
    // after perspective division
    int perX, perY;

    // scale
    //float scale = 2f;

    for(int pixelY = toCenterOffsetY; pixelY < screenH; pixelY++) {
        for(int pixelX = 0; pixelX < screenW; pixelX++) {
            // z
            screenZ = z;

            // translating to center
            screenY = pixelY - (texH >> 1);
            screenX = pixelX - (texW >> 1);

            // transformation

            // rotating -- glitch like graphic somehow
            //tempX = screenX * Math.cos(rotY*RAD) - screenY * Math.sin(rotY*RAD);
            //tempY = screenX * Math.sin(rotY*RAD) + screenY * Math.cos(rotY*RAD);
            //screenX = tempX;
            //screenY = tempY;

            // 3D Rx
            //               | x |
            //               | y |
            //               | z |
            // ----------------------------------------------
            // | 1  0    0   | 1 * x + 0 * y + 0 * z     = x'
            // | 0  cos -sin | 0 * x + cos * y - sin * z = y'
            // | 0  sin  cos | 0 * x + sin * y + cos * z = z'
            tempX = screenX * 1 + 0 * screenY + 0 * screenZ;
            tempY = screenX * 0 + screenY * Math.cos(rotX*RAD) - screenZ * Math.sin(rotX*RAD);
            tempZ = screenX * 0 + screenY * Math.sin(rotX*RAD) + screenZ * Math.cos(rotX*RAD);

            // rotating
            tempX = screenX * Math.cos(rotY*RAD) - screenY * Math.sin(rotY*RAD); // rotates Z instead of Y
            tempY = screenX * Math.sin(rotY*RAD) + screenY * Math.cos(rotY*RAD);
            screenX = tempX;
            screenY = tempY;

            // translating back
            screenY = (float) tempY; // + (texH >> 1);
            screenX = (float) tempX; // + (texW >> 1);

            // perspective divison and set horizon
            perX = (int) (screenX / tempZ) + toCenterOffsetX;
            perY = (int) (screenY / tempZ) + toCenterOffsetY;

            // index
            //pixelX *= scale; // not working, blank blue screen
            //pixelY *= scale;

            // removing gaps with nearest neighbour like scaling
            //pixelX *= texW / (texW / tempZ);
            //pixelY *= texH / (texH / tempZ);
            // simplified
            //pixelX *= tempZ;
            //pixelY *= tempZ; // not working...even one frame won't be drawn, just white screen

            textureIndex = (int) ( pixelY * texW + pixelX );

            screenIndex = (int) ( perY * screenW + perX );

            // write pixels
            if( (textureIndex >= 0 && textureIndex < imgWH) &&
                (screenIndex >= 0 && screenIndex < scrWH)
            ) {
                output[screenIndex] = input[textureIndex];
            }
        }
    }
}

```

If I'm right, then I should use something similar to the nearest neighbour scaling to remove the gaps.

Games like Outrun doesn't have a huge map eg. 3000 x 3000 (I think) but it'll take minutes to drive through the picture. I first used a 64 * 64 texture for this but ther results were almost exactly the same. How could I make the map scaled to the proper size?

I leave the optimizations for later.

The input / output arrays are due to the DataBufferInt and getRGB(x, y, w, h... stuff I used to avoid setRGB and other slow methods.

I don't ask for exact, full solutions, I ask for some hints, guides, or mathematical explanations.

I'd like to learn enough so I can create a simple 3D game like Notch did. I know he's already had years of experience of game programming but I hope it's something I can learn without 10+ year of game programming.

Here are the results and the used texture:

(Sorry for my bad English.)

# Answer
Outrun and Space Harrier don’t use mode7 like engines. I recommend reading Louis Pseudo3D page for indepth reading. Also Jake Gordon’s Javascript Outrun for code and technique examples.

In general the road is split up in segments. Think of each segment being the width of the road and about a meter deep. The road is then defined as an array of these segments. Each segment defines an angle if the segment creates a curve. One could include more information in each segment- roadside objects or properies of the road like surface type (ice, mud or asphalt) to have gameplay elements interact with it. This is how many racegames define the long routes.

Each segment is then drawn using the painters algorithm starting with the one in the distance until the segment near the camera is reached.

Drawing a segment is translating a 3D rectangle to screenspace. Thus the entire road is a stretch of rectangles stacked after oneother. This looks much like your attempt with pseudo 3D code- however it can be done equally with matrices etc.

Thus the effect you are looking for (Outrun, Space Harrier) is not a Mode7 effect. Mode7 is used in Mariokart and F-Zero (SNES) it produces a different type of road with smaller- usually looped laps. Also Notch game likely uses a different technique called raycasting also seen in the original Wolfenstein3D and Doom games.
> 1 votes

# Answer
You have to make slices closer to the camera wider. pick a large enough value and divide it by the z coordinate. If there are still gaps, try making that arbitary value larger
> 0 votes

---
Tags: 3d, graphics
---


# Question
Title: How to use arrow keys to navigate between cells in a crossword puzzle
I am making a crossword puzzle, using a canvas.

How do you get the keyboard arrows to interact with the screen so that when the user presses any of the arrow keys, the cursor will advance to the next available input block.

This is how I drew the blocks on the canvas, with css styles added, button 1 and button 2: The "names001" stands for each box in the puzzle, then each box is assigned a letter value:

```
var r = event.keyCode;
if (r == 13 && m003 == "c") {
    w003 = 1;
    document.getElementById("names003").value = "c";
}

```

then a variable checks to see if each word is right and places a checkmark beside clue:

```
var check001 = w010 + w011 + w012 + w013 + w014;
if (check001 == 5) {
    clue001.innerHTML = "✔"
}

```

Now, I want to know when the puzzle is drawn to the canvas, how do you get the keyboard arrows to interact with the canvas when the user presses one of the arrows(up, down, left, right and also the backspace to clear entry when guess is wrong; I want to move the cursor to advance to the next block.

# Answer
> 1 votes
Assuming your crossword puzzle is a 2D array, I'll call it `grid`, containing all blocks (even ones that do not expect a letter):

* Create 2 integers, `selection_x` and `selection_y` initialised at 0.
* Create a new object, let's name it `highlight`, set it's `x` and `y` the same as `grid[0][0]`. This object shows to the user which cell is highlighted, how it does that depends on you.
* Every time an arrow key is pressed, increase/decrease `selection_x` or `selection_y` (depending on which button is pressed, check to make sure it's still inside the grid, then change `highlight`'s position to `grid[selection_x][selection_y]`.

This is enough for a basic setup, here are a few extra ideas:

* Every time a key arrow is pressed, change the value of the selection only if the new cell accepts a letter (and is not an empty cell). This may need to change the initial cell to the first active one, instead of `0, 0`.
* Change the color of the highlighted cell, when an arrow key is pressed change current selection to (let's say) white: `grid[selection_x][selection_y].color = white;`, then change the value of `selection_x`/`selection_y`, then change the new cell's color to (let's say) red: `grid[selection_x][selection_y].color = red;`

Note that all code is pseudocode, since you haven't shared much about your project, I can't make it more specific.

---
Tags: javascript, html-canvas
---


title: Animate some tiles of tile map

text:
# Question
Title: Animate some tiles of tile map
I have a game where each "tile" of the terrain is a triangle (Settlers 2). Those are placed next to each other and in way creating an infinite world (right/bottom jumps back to left/top). There is a 3D component (each triangle point has a height) but that gets translated into an Y-position offset, so everything can be considered 2D.

Everything (texture coords, screen coords, color (white\<-\>black, FoW)) is put into VBOs already and usually does not change (FoW may disappear which updates the color VBO, but rarely)

When drawing I iterate over the visible tiles (currently in view) and collect "runs" of tiles with the same texture. After that I do:

* Bind current texture
* Draw current run (offset into VBOs + num of same textured tiles)
* Repeat until all runs are drawn

To reduce the number of texture switches I wanted to create a texture atlas. But the problem: Some textures are animated (texture animation so all tiles use the same frame of the animation at any given time) and those animations may be different.

To give some numbers:

* ~30 textures, pretty small (~30-60px each)
* 8 are animated, rest static
* animation length is 4-8 frames
* animation frame time is constant

How would I best go with those animations?

* Put all static textures into 1 texture, animated ones into separate ones?
* Unroll animations so I have ~8 textures (possibly 24 if I have 8 frame and 6 frame animations) where each texture is 1 frame (so static textures are copied into those unmodified)
* Repeat all textures into 1 texture and do some U-coordinate shifting in a shader (not used ATM, but will add soon) -\> again possible waste
* Some shader magic?

Using OpenGL 2.1, C++.

Visualization of 3 textures: Triangles cut out from squares in any position (in fact only 6 are possible: Top to bottom, top to middle, top to middle rotated by 135° and their mirrored counterparts). Shown is 1 of 2 triangles per square, the other one is mirrored horizontally. All tiles may have different sizes

# Answer
> 1 votes
I'd recommend doing this in your shader.

1. Arrange your atlas so that subsequent frames of each animation are arranged consecutively in a row. No duplication of non-animated tiles required.
2. Use 3D UVW coordinates for each tile vertex. The first two values point to the corners of the start frame of the animation in the atlas (the only frame, for non-animated tiles) and the third coordinate is the length of the animation (1 for non-animated tiles)
3. Pass a uniform to your shader representing the current frame number (increasing from 0 to a common multiple of all your animation lengths before wrapping back around)
4. In your vertex shader, take this frame number modulo your animation length read from the UVW coordinates. Use this result to offset the horizontal coordinate by that many tile steps, and pass the resulting 2D UV coordinates down the pipe to your fragment shader.

---
Tags: opengl, animation, texture-atlas
---


# Question
Title: Simple coherent noise function to use in a GLSL shader
I'm looking for a simple (but especially fast) coherent noise function to use it in a shader written in GLSL.

I don't need it to be excessively smooth or good looking, I just need that it has the following properties:

1. Passing in the same input value will always return the same output value.
2. A small change in the input value will produce a small change in the output value.
3. A large change in the input value will produce a random change in the output value.

I really need it to be *fast*, as it will be called once for each pixel by the GPU (to have an idea of how fast it should be, I tried Perlin Noise and it crashed my application).

What method should I use? I'd also like if the same pattern didn't repeat over time.

# Answer
> 3 votes
The best you can do is using a texture to get the noise from, note that this is not the same as sampling a noise texture, you are just getting the random values from the texture so you can animate it as a normal noise function. This makes it really fast. If you input the same parameters you will return the same output, and the change in the input value goes according to the change in the output value.

```
// Courtesy of Iñigo Quilez.
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 );

}

```

This one is also very fast and actually some smartphones may be better off with no texture calls (faster? I am not sure. You'll have to test)

```
// Pseudo random number generator.
float hash( vec2 a )
{

    return fract( sin( a.x * 3433.8 + a.y * 3843.98 ) * 45933.8 );

}

// Value noise courtesy of BigWingz
// check his youtube channel he has
// a video of this one.
// Succint version by FabriceNeyret
float noise( vec2 U )
{
    vec2 id = floor( U );
          U = fract( U );
    U *= U * ( 3. - 2. * U );

    vec2 A = vec2( hash(id)            , hash(id + vec2(0,1)) ),
         B = vec2( hash(id + vec2(1,0)), hash(id + vec2(1,1)) ),
         C = mix( A, B, U.x);

    return mix( C.x, C.y, U.y );
}

```

The algorithm is pretty simple, you create tiles with your UV's and you assign a random colour to each of the tiles, then you interpolate between them.

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 go for the texture based approach you need this texture to get the noise function to work:

Remember to not VFlip it and to have it as GL\_REPEAT with MipMap filters.

WebGL Noise2D Demo, comment the VALUENOISE define to see the texture noise.

And a post that I wrote that may be related.

---
Tags: shaders, glsl, gpu, noise
---


# Question
Title: How to check if all switch objects in a room are set to true?
I'm trying to implement a puzzle mechanic in Game Maker Studio 2.
Where you need to activate multiple switches for an event to happen (e.g. opening a door)

However, I'm currently stuck in recieving the booleans from *all* switch objects in a room.
Currently It's only working when *any* (or only the first) switch is hit.

Here's an example of how it works:

Switch collision with projectile:

```
switched = !switched

```

'Switchdoor' step event:

```
if (switch.switched == true) //this only seem te register the first switch placed
{
    //do action
}

```

If I've used XNA, I could make a `List<>` to store all the rendered switches and get their boolean values. But what can I use instead in Game Maker Studio 2, who works with rooms?

# Answer
If my GML is not too rusty, the following should work:

```
var allSwitchesOn = true;

with(switch) {
    if(!switched) {
        other.allSwitchesOn = false;
        break;
    }
}

// allSwitchesOn now has the correct value

```
> 6 votes

---
Tags: game-maker, game-maker-studio-2
---


# Question
Title: Using single Triggers on multiple controllers in Unity
After trying out a lot of stuff I finally need to surrender. Im having a project where I want to use the triggers of the Xbox Controllers seperately. To do so I added them as axis 9 and 10 in the input manager (see image). Now, when i have multiple controllers connected on project startup the triggers wont get recognized. I have to press the trigger on two controllers to get a value from it...prettty strange. If i reconnect the controllers after project launch everything works fine...

Test script looks like this.

Thanks!

# Answer
I had the same issue on our third person local co-op shooter game and I've burned countless hours only to conclude that it's bugged. I recommend ditching Unity's InputManager and use XInputDotNet (https://github.com/speps/XInputDotNet). Using this lib instead fixed all the issues I had with multiple controllers and trigger buttons. One caveat: it's not going to work on the OSX. As an alternative, you can then try XBoxCtrlrInput lib. It boasts OSX support but I can't fully vouch for it as I've only used it briefly (https://github.com/JISyed/Unity-XboxCtrlrInput).
> 1 votes

---
Tags: unity, input, controllers, xbox
---


# Question
Title: Meshes exported from blender as .obj does not map correctly
I am having some problems with developing my game in OpenGL with java (Using LWJGL3). I have been following a guide for the more complex steps of the process, like loading meshes.

When using the basic mesh of a cube that was provided by the guide it works as it should, so it seems like it is not my software that is the problem? The problem comes when I attempted to create my own models using blender. I made sure to triangulate faces and include normals when exporting, but for some reason even when I created a simple cube it does not work correctly. The textures get smeared, only one face is intact. I have both tried the automatic UV projection, and making my own seams.

I have been stuck on this for a while and I have no idea where I am doing something wrong. I would greatly appreciate some help.

# Answer
Did you export the UV coordinates?

Did you unwrap the model?

Maybe this answer can help you.

Is the OBJ file loader provided by WJGL3? Or did you roll your own? If it's the latter.. note that OBJ indices start counting at 1, not 0. This easily trips up any programmer trying to parse Wavefront OBJ files.
> 1 votes

# Answer
It turned out to be a small and stupid mistake. I had forgotten to split the edges, with the "Edge Split" action in blender. My game engine could not assign multiple texture coordinates to the same vertex so I had to give every face its own vertices. Nice.
> 1 votes

---
Tags: java, textures, lwjgl, blender
---


# Question
Title: How to use separating axis theorem to allow for sliding along walls
I'm making a 2D platformer game and using the separating axis theorem for collision detection, but I want the player to be able to walk along the ground and slide on walls and other stuff and I can't find anything online.

For moving I have:

```
//in my Entity class, where each entity has a collider
//and is added to the world on creation
public void Move(Vector amount)
{
    Pos += amount;
    if(world.isCollidingWithAnything(this))
    {
        Pos-=amount;
    }
}

```

If I move into a collision it stops all movement that frame, even if the movement is parallel to the obstacle. How do I make it to where they can walk along the ground without splitting the x and y movement?

# Answer
Separating axis doesn't mean you *have* to split along x and y. You can pick other bases.

Make the axes the normal perpendicular to the wall and the tangent along the wall.

Then you can set the speed and movement along the normal to 0 and keep the speed and motion along the tangent as is.
> 1 votes

# Answer
Is a top down or a platformer 2D game? Assuming it's a top down, what you want to do is to compare the movement amount vector to the normal of the wall that you've hit. Your two most extreme cases will be these:

1) Your movement vector and wall normal are parallel - you've hit the wall head on and you want to stop completely.

2) Your movement vector and wall normal are perpendicular - you're moving prefectly along the side of the wall and want to keep the same speed.

Anything between these two cases you want to interpolate - meaning if you've hit the wall, for example, at a 45 degree angle you most likely you want to slide along the wall but at 50% of your speed.

Here's how you can achieve this using a Cross Product and Vector Projection.

First you want to find your wall tangent (or "vector along the wall"), again assuming it's a top down game:

```
wallTangent = Vector.Cross(wallNormal, Vector.up);

```

Great, you have base vector for moving along the wall. Now you need to achieve the interpolation that I've mentioned between hitting the wall completely and perfectly sliding along, depending on the angle that the character hits the wall. For this you can use Vector Projection.

```
movementAlongWallAmount = Vector.Project(movementAmount, wallTangent)

```

Note: this code does not handle "pushing out of collision", I'm assuming you already have this working on a different system.
> 1 votes

---
Tags: c#, collision-detection, collision-resolution, separating-axis-theorem
---


# Question
Title: How to reset the score to 0 when reloading the game?
My scoring system uses DontDestroyOnLoad to persist between scenes:

```
public class ScoringSystem : MonoBehaviour {
 private int score = 0;

 public void Correct(int number){
     // If correct add score;
     score = score + number;
 }

 void Start () {
     score = 0;
 }

 void Awake() {
   DontDestroyOnLoad(transform.gameObject);
 }

 public int GetScore(){
     return score;
 }
}

```

Here is another script that I should include a description about:

```
  public void iniTag()
 {
     jawab = true;
     Time.timeScale = 0;

         GameObject objek1 = GameObject.FindGameObjectWithTag("Benar1");
         GameObject objek2 = GameObject.FindGameObjectWithTag("Benar2");
         GameObject objek3 = GameObject.FindGameObjectWithTag("Benar3");
         GameObject objek4 = GameObject.FindGameObjectWithTag("Benar4");

         if (objek1.transform.parent.tag == "Jawab4" && objek2.transform.parent.tag == "Jawab3" &&
             objek3.transform.parent.tag == "Jawab2" && objek4.transform.parent.tag == "Jawab1")
         {
             PanelBenar.SetActive(true);
             buttonNext.SetActive(true);
             GameObject.Find("QuizManager").SendMessage("Correct", playerScore);

     }}

     void Start () {
       if (GameObject.Find ("QuizManager") != null) {
         ScoringSystem scoringSystem = GameObject.Find ("QuizManager").GetComponent<ScoringSystem> ();
         gameObject.GetComponent<Text>().text = scoringSystem.GetScore().ToString ();
             } else {
         Debug.Log("No Scoring system found. To test scoring system start from the front page scene");
       }
     }

```

# Answer
Here's what you want to do, most likely ('...' means omitted code):

```
using UnityEngine.SceneManagement;

public class ScoringSystem : MonoBehaviour {
 ...

 bool registeredForSceneCallback = false;

 ...

 void Start ()
 {
     if (!registeredForSceneCallback)
     {
         SceneManager.sceneLoaded += OnSceneLoaded;
         registeredForSceneCallback = true;
     }
     score = 0;
 }

 void OnSceneLoaded(Scene scene, LoadSceneMode mode)
 {
    score = 0;
 }

 ...
}

```

Additionally, inside the OnSceneLoaded method you might want to check that the scene.name value matches the scene that you're reloading on restart.

For more info on how to receive callbacks from SceneManager take a look at: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html
> 3 votes

# Answer
I believe, simplest way to do this is manually reset score when you actually restart the game.
> 2 votes

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


title: Twine game animated blur effect

text:
# Question
Title: Twine game animated blur effect
I'm making a horror text adventure using Twine (snowman version, which uses HTML, CSS, Javascript, JQuery, and Markdown). I wanted to know what the best (easiest) way is, you think, for creating a foggy effect where the text comes in and out of focus (adding/removing blur to lines, words, or characters) based on some criteria (mouseover, text advancement, or time).

Or, just, any way of doing it.

I'm really new to Javascript, just picked it up this week, but with a long history of web design and (bad) hobby coding. (Python, Lua)

I'm interested in understanding the logic behind it, since I intend to spend time on web-based game development, so err on the side of elaboration please.

And of course, let me know if the question is faulty or needs clarification. Thanks!

# Answer
Generally speaking, the `SugarCube` format is more powerful, if you want to use Javascript.

For your question, you just have to put `<<script>>` `code here` `<</script>>`

To produce the blur effect, you have different options (html5, js, css...)

For Twine it would be more convenient to do directly with JS, by example :

https://youtu.be/-abN0TPy0kU?t=50
> 1 votes

---
Tags: javascript, web, text-based, html, css
---


# Question
Title: Stretching limited graphic assets in a loot based game
I’m creating a game with a fairly simple gameplay. The battle will be similar to rock, paper, scissors but with stat components where your choice combined with your stats determines the winner. It has limited graphics however it’s weapon based so you weapon will be shown. Therefore I think it’s be more fun to focus a lot on loot and upgrading the visual of the weapons and other properties of your character that you’re using in battle.

The problem is I have a fairly limited budget to start so I’m trying to determine the best way to stretch my graphic assets and number of weapon yet still make the game interesting.

The options I’ve considered so far:

1) At the end of every game you get a new random weapon/weapon skin. This is the most fun but also would require the most skins as you’ll run through them really quick.

2) When you win you win a random weapon skin, you then have to combine them in some way like 3 tier 1 skins equals 1 tier 2 skin, and 3 tier 2 skins equals 1 tier 3 skin. This is a nice middle balance.

3) You only win stat increases, you must pay for new skins if you want to upgrade your cosmetics. This is the least fun way as your “loot” isn’t very appealing, but I would only need a few assets in the store to start.

I’m hoping by asking this I can find quality and creative ways to approach this issue that I wouldn’t have otherwise thought of. I know there is no “best” so hopefully this question isn’t off topic but Intruly need help here.

# Answer
> 7 votes
When you want to get the most variation out of a small collection of assets, combinatorics can be a major ally.

Let's say we have the budget for 15 art assets to put toward our swords. We could get 15 sword skins, or we could get:

* 3 sword blades
* 3 hand guards
* 3 pommels
* 3 tassels
* 3 gems / inscriptions

By layering one item from each category together, we create a new sword. The total number of swords we can create this way is 3\*3\*3\*3\*3 = 243. And if we add in applying a runtime tint, squash/stretch/twist/warp, or material effect to the image, we can multiply this even further.

Granted, not every one of these swords will feel entirely unique - players are good at picking up on patterns and "chunking" systems like these down to a smaller set of perceived clusters - but it's still going to give you more than 15 distinct reward milestones, even if you use only a fraction of the possibility space.

Making art assets that can combine freely like this is also more challenging / more limiting than making standalone assets, so there will be a trade-off between how much you split out for combinatoric multiplication and how much you reserve for bespoke artistry. When done well though, this kind of technique can be a force multiplier for a small art budget.

---
Tags: assets, balance
---


# Question
Title: GLSL C++ Only first sampler array index is accessible
I have the following shader, which whose fragment shader contains a sampler array of 16 elements.

**Fragment**

```
#version 330 core
in vec2 _uv;
flat in int _instanceID;

out vec4 color;

uniform sampler2D sampler[16];

void main() {
    color = texture(sampler[_instanceID], _uv);
}

```

Now when I try to set the second array element using the following method

```
void Shader::setUniform(const std::string& uniform, GLuint* values, size_t amount) const {
    bindProgram();

    GLuint loc = getUniformLocation(uniform + "[0]");
    for(int i = 0; i < amount; i++){
        glUniform1ui(loc+i, values[i]);
        std::cout << values[i] << " "; //For debug
    }
    std::cout << std::endl; //For debug
}

```

It just sets the first element of the shader. Even though I'm passing 2 values.

**This is the output of the cout's:**

```
5 4
5 4
5 4
5 4
...

```

Looking up the shader variables with GDebugger, only the first element is set.  It also only draws the first (index 0) image.

# Answer
> 1 votes
`getUniformLocation` isn't required to be continuous for array uniforms, so instead of just fetching the location of `"sampler[0]"`, you also need to find the location for `"sampler[1]"` and so on.

---
Tags: opengl, c++
---


# Question
Title: Do industry professionals building games using UE4 use Blueprints at all, or do they use C++ exclusively?
As a teacher on a game development module I have usually insisted that users use C++, because it is a more sought-after skill in industry, but online support and information on C++ in Unreal Engine 4 seems to be relatively weak. Are professionals now using Blueprints as well, or not?

# Answer
Yes, professional games use Blueprints.

Some use a mix of C++ and Blueprints. We use both on Dead by Daylight.

One of the great things about Blueprints is that non-programmers can get access to the ability to script behaviors. Not every project will use them this way, but it's one of the reasons they were designed. They replaced UnrealScript as the means of altering behaviors without hitting the C++, and they also replaced Kismet which was Unreal 3's visual scripting system.
> 25 votes

# Answer
A little anecdote from outside the games industry: We use UE4 for architecture visualization in VR.

While I'd rather have most things built in C++, we also use Blueprints heavily for all kinds of "additional logic" like light switches, doors, etc.

It's been this way for a little over two years now and I was the only programmer at the start of this endeavor. So here are my observations:

* It's astounding what non-programmers can do with Blueprints!
* I can be horrifying what novice programmers do with Blueprints ;)
* Even if I convert it to C++ in the end, Blueprints are nice for a quick RnD phase

And the biggest one for me: In a lot of conversations, it became clear to me that Blueprints have invoked the desire to become programmers in my non-tech colleagues. The main reason this happened is that they could implement quite complex logic while being able to debug it visually.

They actually learned some hard lessons about software architecture and the pitfalls (or rather nightmares) of huge spaghetti blueprints. But only after having felt a ton of little successes along the way! So they weren't discouraged at all but rather motivated to do better and find out how to do so all by themselves.

They've since taken courses in C++, Python, and C#, the overall quality of our Blueprints became way better, but most of all: I now have some help when developing our core libs :)

**TLDR;**

Yes, we're using Blueprints and they even made my initially non-tech peers better coders.
> 10 votes

---
Tags: unreal-4, game-industry
---


# Question
Title: Why only few parts of the 2D sprite change their colour when I apply sprite color in Unity?
I'm making a stickman 2D game where I have different sprites for the player.

But when I try to change the Sprite Renderer Color, it only changes few pixels of the sprite and the rest stays black as in the original sprite.

What am I missing?

# Answer
You've mentioned that the rest of your pixels stay black. The way SpriteRenderer.Color is applied is via multiplication. The mentioned color field does not replace the pixel color but "tints" it. So if you have many black pixels in your sprite, they won't be affected because no matter what color you multiply black (0, 0, 0, 1) by it will remain black.
> 3 votes

---
Tags: unity, 2d, sprites, color
---


# Question
Title: Debug.DrawRay() does not draw rays in game view
Here is the relevant code:

```
protected override void Update()
{
    base.Update();

    Debug.DrawRay(this.transform.position, this.transform.forward * 100f, Color.red, duration: 2f);
}

```

When running the game, I can see the ray being drawn in Scene View.

However, in Game View, no ray is displayed.

As you can see from the screenshot below, **I have already enabled gizmos in Game View.**

What should I do to ensure that rays are being drawn in Game View when debugging?

# Answer
> 7 votes
# `Debug.DrawRay` (and other such functions) *never* draw in the game view

They're *debug* drawings and debug info and output should never appear in the "live" program view, which is supposed to mimic the compiled executable's behavior, which strips all references to `Debug`. If you want to draw in the game window you need top use a `LineRenderer` or other runtime solution (UI objects, etc).

# Answer
> 0 votes
Without an actual screenshot showing the problem, I can only make suggestions that may or may not apply to your situation.

First, make sure that the camera is not pointed directly in the same direction as the ray being drawn. Otherwise it might only show up as infinitely in line.

Second, by default, `Debug.DrawRay` draws lines with depth testing enabled, so if the camera is behind the object, and the ray is being drawn mostly away from the camera, the object itself would obscure the line. Or there could be something else in the way. If this is the only problem, then you could simply disable depth testing:

```
Debug.DrawRay(this.transform.position, this.transform.forward * 100f, Color.red, duration: 2f, depthTest: false);

```

As a sidenote, is there a reason duration is set to 2? Since this is being called in `Update`, no duration is required unless you want it to continue to be drawn after the object is disabled, or if the object is moving or rotating and you want a visual record of where it was in previous frames.

# Answer
> 0 votes
Make sure your component that draws the ray is *expanded* when viewed from the Inspector. If it's collapsed, it won't draw Debug stuff. I've waisted countless hours debugging my * caugh * debugging tools only to find out it's all down to a component being expanded or not.

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


# Question
Title: how to calculate initial Y velocity required to reach target?
I am trying to calculate the y velocity necessary for my player character to jump up and reach a y position within 1 second.

Given that my game engine is at 60fps, I am doing:

```
velY = (targetY - playerY) / 60

```

.. However, I need to account for gravity which is being applied to the character on every update, so I am doing:

```
velY = ((targetY - playerY) / 60) - (gravity * 60)

```

This results in the player character always jumping significantly higher than expect.

**UPDATE**

Attempting to try the Equations of Motion approach, I am setting a timestamp when the player character should begin moving to the target position... So then in my update loop, I am calling a function with currentTime - timestamp.

```
update: function(paceFactor) {
    // paceFactor in this game engine is how many nominal 60FPS game “ticks” have elapsed. So if the game is running at 30FPS, then paceFactor will be 2.0, if it's 60FPS, then 1.0 will be passed in.

  this.timer += paceFactor * (1 / 60);

  if (this.setVelocityAt) {
    this.setVelocityFor(this.timer - this.setVelocityAt, this.targetPoint);
  }

  this.position.x += this.vel.x * this.speed * paceFactor;
  this.position.y += this.vel.y * this.speed * paceFactor;
  this.position.y += (gravity * (paceFactor * paceFactor) * 0.5);
  this.vel.y += gravity * paceFactor;
},

setVelocityFor: function(time, target) {
  if (time > 1) {
    time = 1;
    this.setVelocityAt = undefined;
  }
  this.character.vel.x = (target.x - this.character.position.x) / time;
  this.character.vel.y = (target.y + (0.5 * GRAVITY * time * time) - this.character.position.y) / time;
},

```

Then later the position and gravity is applied to the character as described in the previous update.

However, the velocity being set is a huge number which is... wrong.

# Answer
You are going to need to use the Equations of Motion.

This is because the velocity is not constant over the time frame. You cannot calculate distance traveled by velocity and time alone.

One way to do this is to calculate the distance at each time step. (The other way would be to use a parametric equation based on the calculated start and end points)

How to do this? You know the initial velocity *u*, the time step *t*, and the acceleration *g*.

Using the equations of motion we will find the final velocity *v* and the distance travelled *s*.

```
s = u * t + 0.5 * g * t * t

v = u + g * t

```

Now it's the end of the time step, you can translate the player by distance *s* and set the next initial velocity to be the calculated final velocity.

Edit:

To put it into code, try this to update the y component. It includes the velocity and gravity as well

```
this.position.y += this.vel.y * paceFactor - 0.5 * gravity * paceFactor * paceFactor;
this.vel.y += -gravity * paceFactor;

```

Edit 2:

Here is a javascript snippet that shows how jumping is supposed to work with gravity. You can change the frame increment (paceFactor in your game) and the jumping will be consistent. There is an update loop that basically only changes the value of *y* and *vel\_y*.

```
<html>
<body>
<canvas id="exampleCanvas" width="50" height="300"></canvas>
</body>
<script>
var x = 0;
var y = 0;
var vel_y = 0;
var g = 1;
var c = document.getElementById("exampleCanvas");
var ctx = c.getContext("2d");
var jumpHeight = 250;
var jumpImpulse = Math.sqrt(2 * g * jumpHeight);

function loop(timestamp) {

  // Note that changing update(1) to update(2) changes the speed of the simulation.
  // It does not change how high the player can jump
  update(1);

  // Request the next frame
  window.requestAnimationFrame(loop);
}

function update(t) {

  // Do a jump
  if (y >= 250)
  {
y = 250; // Snap player to the Ground level
vel_y = -jumpImpulse; // Jump speed
  }

  // Do the motion (update y and vel_y)
  var dist = vel_y * t + 0.5 * g * t * t
  vel_y = vel_y + g * t
  y += dist;

  // Draw a square
  ctx.clearRect(0, 0, c.width, c.height);

  ctx.beginPath();
  ctx.rect(x, y, 50, 50);
  ctx.stroke();
}

// Start the loop
window.requestAnimationFrame(loop);

</script>
</html>
```
> 2 votes

# Answer
This should work, given that you want to be at 0 speed along y once you reach it:

```
distY = (targetY - playerY);
velInitialY = Mathf.Sqrt(-2f * gravityY * distY); // Want to make sure what's passed to Sqrt is not negative

```

This assumes that your gravity that you insert here is signed and that this is how you're updating your actual velocity each frame when in air:

```
velY += gravityY * timeDelta;
posY += velY * timeDelta;

```
> 1 votes

---
Tags: physics, projectile-physics
---


# Question
Title: Unity - Trying to copy the render texture for the scene rendered by a camera but it is blank?
I'm trying to copy the scene rendered by a particular camera to a render target. I know this should be possible to do without using the camera's target texture as I read through this official Unity article about Command Buffers which avoids any use of them.

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

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

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

```

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

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

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

The code I am using is

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

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

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

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

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

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

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

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

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

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

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

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

```

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

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

# Answer
Try to remove all calls in `OnRenderObject` except

```
commandBuffer.Blit(BuiltinRenderTextureType.CurrentActive, debugRT);

```

And I believe you don't have to call that one even every time, because it is a state call, so you only have to call it on initialization (in your `Awake` function. (Maybe don't initialize in `Awake`, but in `Start`?)).
> 2 votes

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

```

Here you're setting your current render target tl be the debug RenderTexture.

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

```

Here you're copying from the current render target into the debug RenderTexture.

But wait, the current render target *is* the debug RenderTexture! That's what we set it to just a few lines above. So this call is asking to copy from one buffer into the same buffer, never looking at the scene render target's contents at all.
> 2 votes

---
Tags: unity, c#, rendering, rendertargets
---


# Question
Title: How to stop car from slipping backwards on a slope?
I am trying to simulate a car in Unity, the slope of the road is high so the car slips backwards. Is there any physics property which can stop this from happening?
Thanks in advance.

# Answer
When in park you could mark as kinematic, or a better solution may be increasing the angular & linear drag on the rigidbody to stop it from sliding.

That will also help if there was a collision to the car during runtime. it would drag along from the impact force rather than go flying off at impact speed.
> 1 votes

---
Tags: unity, car
---


title: Rider Language level keeps resetting

text:
# Question
Title: Rider Language level keeps resetting
We've started working with Unity 2018.3.0b11 recently, and this means we can now use newer C# features, which is amazing! However, every time I've restarted Rider, it starts complaining about any C# 7.0 features, like this:

The autofix is to allow ReSharper to suggest C# 7.0 features:

Opening the properties for the assembly will show that the language level has been set back to "latest":

If I change it to 7.3 specifically and close and re-open the settings, it now explains that the settings are overridden in the "Rider Settings" to C# 6.0.

If I click "Reset" it will then work, until the next time I restart Rider and it will be back to the first state above.

Using the "auto-fix" seems to take step one first (change to 7.0 specifically), still complaining though, and then if I do it a second time, it will do the second step ("Reset").

Is anyone else experiencing this with Unity 2018, and have you worked out a permanent fix?

# Answer
Apparently it will be fixed in Rider 2018.3:

https://github.com/JetBrains/resharper-unity/issues/956

So, it's just a matter of waiting for it to be released, or using nightly builds until then...
> 1 votes

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


# Question
Title: RTS Unit AI: When to let the unit stop (due to local avoidence)
I am developing an RTS-like game, that have units that move and attack. I implemented path-finding and local-avoidance.

One problem is when multiple units being ordered to the exact same position, they can never reach the position due local-avoidance and collision.

Only this will make the units scratch each other, this will also cause the unit not able to STOP, as the unit might be still far from the target position. And whether stopped or not is important for battle (unit can only attack when stopped).

I studied how SC2 handles this, it appears that the units will stop after a few seconds of scratching.

PS, I have used group formation to avoid the situation, but it can not be avoided, when the group are ordered to goto some impossible position, and they would cluster at the edge of the valid navmesh.

# Answer
AI War: Fleet Command handles this in two ways.

1) when multiple units are given a move command the game automatically computes unique stopping points for each unit, performing the local avoidance on each unit once knowing what space will be occupied at the destination and calculating dither and further spots away from the user's input by filling circles (that is, units get assigned a position on a circle starting at 0 degrees, when the circle fills up, the radius is increased, and the process repeats).

2) if a unit arrives at its destination and it is bigger than the units it landed on, it bumps the smaller units under it (this keeps things like golems from lumbering around, they bump everything, starships are smaller, but bigger than fleet ships, so they occupy a middle space, and fleet ships are the smallest; stationary units never get bumped). If its a small unit, it gets bumped instead. Bumped units pick a random new location it go to that's nearby (picks a random direction and flies until it finds open space). Usually settles down fairly quickly.
> 4 votes

# Answer
In a case like this, I'd measure the distance between the unit and the target position and if the unit did not get any closer to its target, then I'd also use the unit's last few positions to see if it has moved.

If the unit is not getting any closer to its target and it's not moving an amount you deem good enough, then it's time for this unit to stop.

The following code is just pseudo-code, and it assumes you're going to calculate the distances yourself, so it might not work out of the box, but it's basically what you need in a case like this (or at least some point to start your work from):

```
if((abs(previousDistanceToTarget - currentDistanceToTarget)) <
    predefinedGranularMovementAmount)
{
    /*
    CalculateMovementAmount function calculates how much the unit's
    position has changed in the last few seconds or even in the last
    second depending on your personal preference
    */
    unitMovementDistance = CalculateMovementAmount();
    if(unitMovementDistance < predefinedGranularMovementAmount)
    {
        CancelUnitMovementOrder();
    }
}

```
> 2 votes

# Answer
increasing the stopping distance on the nav mesh agent allows you some space to line up around the selected goal position. That way if the goal location is crowded they will select the next closest distance within the range to stop.

you can also dynamically increase this if you have larger groups heading to one position. maybe setup a threshold so the stopping distance would be 2 unless more than 5 moving there then it can increase to 4 and so on.
> 1 votes

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


title: Tiled tmx format into 3d Texture

text:
# Question
Title: Tiled tmx format into 3d Texture
I am thinking of making 3d games with 2d pixels feel. So far, i have been playing around in tiled and monogames. I learned some xml and managed to import and render tmx into my game. This is maybe a dumb question. How do you convert tmx into 3d texture? What kind of software do you need?

# Answer
> 2 votes
You can create a mesh programmatically that corresponds to a tmx tilemap. A tilemap consists out of two things: the tilemap and the texture.

I know the TMX format is not immediate in X,Y coordinates, but since you already experimented with the format, I assume for the same of simplicity that you can convert a tile index to the corresponding X,Y coordinate.

In Monogame you can use an array of `VertexPositionTexture` to accomplis this.

To generate the 3D mesh is basically quads like this:

```
+---+---+---+
|\  |\  |\  |
| \ | \ | \ |
|  \|  \|  \|
+---+---+---+
|\  |\  |\  |
| \ | \ | \ |
|  \|  \|  \|
+---+---+---+
|\  |\  |\  |
| \ | \ | \ |
|  \|  \|  \|
+---+---+---+

```

The vertices are the tile coordinates these are calculated by the tilemap location (repeat for each quad- keep the Z coordinate at 0):

```
(tile.x, tile.y) —--- (tile.x+1,tile.y)
       |                         |
       |                         |
(tile.x, tile.y+1) --- (tile.x+1,tile.y+1)

```

Now comes the tricky part: the textures. The tiles in the texture is basically one spriteatlas. The coordinate for a spriteatlas tile should be divided by the width and height of the image. The reason is that the textures coordinates in the GPU range from 0,0 to 1,1. So if the dimension of the image is 640x480, and each tile is 16x16, the tile at on the GPU is 16/640 = 0.025 wide and 0.0333 high. Thus the spriteatlas tile at (x,y) would be:

```
(x*0.025, y *0.033) ------ ((x+1)*0.025,y*0.033)
       |                      |
       |                      |
(x*0.025, (y+1)*0.033) --- ((x+1)*0.025,(y+1)*0.033)

```

combine the mesh above with the texture coordinates for each vertex out of the texture atlas from the TMX xls and you have the map as a 3D mesh.

With this knowledge, you can convert objects in the TMX file to replace them with 3D models- or even generate 3D models are specific 'Tiled' terrains. Combine this further with heightmaps, or flowmaps and convert the Tiled coordinates as a basis for all kinds of objects.

---
Tags: c#, monogame, tiled
---


# Question
Title: Piece of code causes game to freeze, then keep playing after sometime
## Games Basic Premise

Ball rolls along procedurally generated path. Click to changer directions. Don't fall off. I have a script dedicated to the path. The path is made up of 20 cubes, along the x+ and z+ axis. Path is generated at the start then changes randomly as you go.

## Problem

In my path designer script, I also control another cube I call "Fake Path". It's a single cube to throw off the player. But whenever the control script runs it freezes my game, I'm assuming it's processing something. Then after awhile it **might** resume the game. I know my code is probably a little wonky since I'm still getting the basics of game design. `Key_CircLinkList` is a circular linked list. With each element storing an index.

```
void Start(){
    sphere = GameObject.Find("Sphere");
    sphereScript = sphere.GetComponent<SphereMove>();
    startingCube = GameObject.Find("StartCube");
    fakeCube = GameObject.Find("FakeCube");
    randIndex = 10;
    isGenerated = true;

    pathV2 = new Key_CircLinkList<GameObject>();
    pathV2.AddFirst(startingCube);

    for (int i = 0; i < pathLength-1; i++)
    {
        float random = Random.value;
        pathV2.AddLast(Instantiate(startingCube, this.transform));
        if (random <= 0.5f)
        {
            pathV2.GetLast().GetElement().transform.position = new Vector3(pathV2.SelectInd(i).GetElement().transform.position.x + distMove, pathV2.SelectInd(i).GetElement().transform.position.y, pathV2.SelectInd(i).GetElement().transform.position.z);
            //Setting initial movement direction
            if (i == 0)
            {
                sphereScript.l_or_r = true;
            }
        }
        else
        {
            pathV2.GetLast().GetElement().transform.position = new Vector3(pathV2.SelectInd(i).GetElement().transform.position.x, pathV2.SelectInd(i).GetElement().transform.position.y, pathV2.SelectInd(i).GetElement().transform.position.z + distMove);
            //Setting initial movement direction
            if (i == 0)
            {
                sphereScript.l_or_r = false;
            }
        }
    }
    if (pathV2.SelectInd(randIndex).GetNext().GetElement().transform.position.x >
        pathV2.SelectInd(randIndex).GetElement().transform.position.x)
    {
        if (pathV2.SelectInd(randIndex).GetNext(2).GetElement().transform.position.z > pathV2.SelectInd(randIndex).GetElement().transform.position.z){
            fakeCube.transform.position = new Vector3(pathV2.SelectInd(randIndex).GetNext().GetElement().transform.position.x + distMove,
                                                      pathV2.GetSelect().GetElement().transform.position.y,
                                                      pathV2.SelectInd(randIndex).GetElement().transform.position.z);
        }else{
            fakeCube.transform.position = new Vector3(pathV2.SelectInd(randIndex).GetElement().transform.position.x,
                                                      pathV2.GetSelect().GetElement().transform.position.y,
                                                      pathV2.SelectInd(randIndex).GetElement().transform.position.z + distMove);
        }
    }else{
        if (pathV2.SelectInd(randIndex).GetNext(2).GetElement().transform.position.x > pathV2.SelectInd(randIndex).GetNext().GetElement().transform.position.x){
            fakeCube.transform.position = new Vector3(pathV2.SelectInd(randIndex).GetNext().GetElement().transform.position.x,
                                                      pathV2.GetSelect().GetElement().transform.position.y,
                                                      pathV2.SelectInd(randIndex).GetElement().transform.position.z + distMove);
        }else{
            fakeCube.transform.position = new Vector3(pathV2.SelectInd(randIndex).GetElement().transform.position.x + distMove,
                                                      pathV2.GetSelect().GetElement().transform.position.y,
                                                      pathV2.SelectInd(randIndex).GetElement().transform.position.z);
        }
    }
    isGenerated = false;
    cubeX = pathV2.GetLast().GetElement().transform.position.x;
    cubeZ = pathV2.GetLast().GetElement().transform.position.z;

    updatedX = cubeX;
    updatedZ = cubeZ;
}

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

private void SpawnCube()
{
    float random = Random.value;
    //Updates path to move cubes by seeing if (position of the first cube) < ((position of the sphere) - however long the trail of cubes should be)
    if ((pathV2.GetSelect().GetElement().transform.position.x + pathV2.GetSelect().GetElement().transform.position.z) < ((sphere.transform.position.x + sphere.transform.position.z) - 5.0f))
    {
        if (random <= 0.5f)
        {
            updatedX = updatedX + distMove;
            pathV2.GetSelect().GetElement().transform.position = new Vector3(updatedX, pathV2.GetSelect().GetPrev().GetElement().transform.position.y, updatedZ);
        }
        else
        {
            updatedZ = updatedZ + distMove;
            pathV2.GetSelect().GetElement().transform.position = new Vector3(updatedX, pathV2.GetSelect().GetPrev().GetElement().transform.position.y, updatedZ);
        }
        pathV2.Rotate(1);
    }

    if(isGenerated == false){
        randIndex = pathV2.SelectInd(prevIndex).GetNext(10).GetIndex();
        prevIndex = randIndex;
        isGenerated = true;
        Debug.Log("Random Index: " + randIndex);
    }

    if ((fakeCube.transform.position.x + fakeCube.transform.position.z) + 2 < (sphere.transform.position.x + sphere.transform.position.z) &&
        ((pathV2.SelectInd(prevIndex).GetElement().transform.position.x + pathV2.SelectInd(prevIndex).GetElement().transform.position.z) > (sphere.transform.position.x + sphere.transform.position.z))
       ){
        if (pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x > pathV2.SelectInd(prevIndex).GetElement().transform.position.x){
            if(pathV2.SelectInd(prevIndex).GetNext(2).GetElement().transform.position.z > pathV2.SelectInd(prevIndex).GetElement().transform.position.z){
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x+distMove,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z);
            }
            else{
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetElement().transform.position.x,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z + distMove);
            }
        }else{
            if (pathV2.SelectInd(randIndex).GetNext(2).GetElement().transform.position.x > pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x)
            {
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z + distMove);
            }
            else
            {
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetElement().transform.position.x + distMove,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z);
            }
        }
        isGenerated = false;
    }
}

```

When this bit runs, it freezes:

```
if ((fakeCube.transform.position.x + fakeCube.transform.position.z) + 2 < (sphere.transform.position.x + sphere.transform.position.z) &&
        ((pathV2.SelectInd(prevIndex).GetElement().transform.position.x + pathV2.SelectInd(prevIndex).GetElement().transform.position.z) > (sphere.transform.position.x + sphere.transform.position.z))
       ){
        if (pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x > pathV2.SelectInd(prevIndex).GetElement().transform.position.x){
            if(pathV2.SelectInd(prevIndex).GetNext(2).GetElement().transform.position.z > pathV2.SelectInd(prevIndex).GetElement().transform.position.z){
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x+distMove,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z);
            }
            else{
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetElement().transform.position.x,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z + distMove);
            }
        }else{
            if (pathV2.SelectInd(randIndex).GetNext(2).GetElement().transform.position.x > pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x)
            {
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetNext().GetElement().transform.position.x,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z + distMove);
            }
            else
            {
                fakeCube.transform.position = new Vector3(pathV2.SelectInd(prevIndex).GetElement().transform.position.x + distMove,
                                                          pathV2.GetSelect().GetElement().transform.position.y,
                                                          pathV2.SelectInd(prevIndex).GetElement().transform.position.z);
            }
        }
        isGenerated = false;
    }

```

Any help as to what to do, and maybe tips, that would be awesome.

# Answer
> 1 votes
I originally started with an array, everything worked fine. I changed to a `Linked List` to allow for easier implementation of the path. But I decided to switch back to the `Array` implementation. I was reading online that `Linked List`'s are slower than an array, especially with `MonoBehavior`. And what I assume, is that it's so much slower, that when I would run that piece of code, it would take much longer than the `Array`. To the point where it would freeze until it finished. I took @DMGregory advice to use a breakpoint to see what my code was doing. And it worked normally, but with the extended time it took to finish.

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


# Question
Title: Perlin Noise generation always returning zero
I am using noise and I can't get Perlin Noise working, only the Simplex Noise. So far I got this:

```
import noise

values = list()
string = str()
oct = 1

for y in range(20):
    print("[", end = "")
    for x in range(40):
        i = round(noise.snoise2(x, y, octaves = oct), 5)
        values.append(i)
        if i > 0.3:
            print("#", end = "")
            string = string + "#"
        else:
            print("-", end = "")
            string = string + "-"
    print("]\n", end = "")

```

When I try to use Perlin noise instead, I get a value of zero for every x & y.

# Answer
A quick recap of how Perlin noise works:

It starts by finding the cell your sample point lands in within an integer lattice. From that it determines the integer points that define the corners of that cell. For each corner, it generates a pseudo-random gradient vector, and then computes the projection of your sample point's offset from the corner along this gradient vector. Interpolating those projections according to your sample position gives the final smooth noise value.

So, let's consider how this works when your sample lands directly *on* one of these corner points. The interpolation weight for all the other corners will be zero, and the projection onto this corner's gradient vector will also be zero, so the result is: zero.

At every set of integer coordinates, Perlin noise will give you a value of zero.

So, easy fix: don't sample at integer coordinates. Sampling at (x + 0.5, y + 0.5) for integers x & y will move your sample point from the corner to the center of the cell. You won't see much benefit of using a continuous noise function like Perlin noise that way though. Adjacent samples will have little correlation. If you want just a random number per tile, you could use a hashing function like Perlin noise uses internally to select a random gradient for each corner - skipping the overhead of doing it four times, computing dot products and interpolating the results.

Or, if you want continuity across multiple tiles, you should scale your sampling locations smaller than the feature size of the noise function. For instance, if you want large-scale features on the order of about 30 tiles wide, divide x & y by 30 to get a fractional sampling location that will gradually ramp up & down the hills and valleys within each grid cell of the noise function.
> 3 votes

---
Tags: python, perlin-noise
---


# Question
Title: How would I swap a character when a player touches a collider?
I wrote a simple script to attempt to do this and I created an empty game object and applied the script to it and dragged both of my sprites into my script and I receive no errors but nothing happens when my player enters the collider and the "Calm" version of the sprite is still active.

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

public class JetAnglerSwap : MonoBehaviour {
public GameObject CalmAngler;
public GameObject AngryAngler;
// Use this for initialization
void Start () {

}

void OnTriggerEnter2d(Collider2D other)
{
    if (other.CompareTag("Player"))
    {
        SwapAnglers();
    }
}
    void SwapAnglers()
{
    CalmAngler.gameObject.SetActive(false);
    AngryAngler.gameObject.SetActive(true);
}
}

```

# Answer
> 0 votes
Well my workaround here was to create an empty game object called AggroArea and apply this script to it along with a box collider 2D of the size of my water area. When the player jumps in it immediately swaps from one of my public enemy sprites to the other one. It does this by counting the collision of the player as it makes contact with the collider of the water. I have the option to have it do something by writing something in the offstate function but as of now I don't need offstate to do anything.

```
public class JetAnglerSwap : MonoBehaviour {
int playerCount = 0;
public GameObject CalmAngler;
public GameObject AngryAngler;

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player")
    {
        playerCount++;
    }
    else
    {
        playerCount = 0;
    }
}

void Update()
{
    if (playerCount == 2)
    {
        // default on state
        OnState();
    }

    else
    {
        // default off state
        OffState();
    }
}

private void OnState()
{

    CalmAngler.gameObject.SetActive(false);
    AngryAngler.gameObject.SetActive(true);
}
   private void OffState()
  {

  }
}

```

---
Tags: unity, c#, collision-detection, ai
---