# Question
Title: Unreal Crashing just by me adding components
I have created an actor cpp class called gun base. for some reason it is causing a perpetual crash in unreal.

this is its header file.

```
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "GunBase.generated.h"

UCLASS()
class GIZMOSHOOTER_API AGunBase : public AActor
{
    GENERATED_BODY()

public:
    // Sets default values for this actor's properties
    AGunBase();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;
    //virtual void PullTrigger();

private:

    UPROPERTY(EditDefaultsOnly)
    USoundBase* FireSound;
    UPROPERTY(EditDefaultsOnly)
    UParticleSystem* MuzzleFlash;

    UPROPERTY(EditDefaultsOnly)
    USceneComponent* RootSceneComponent = nullptr;
    UPROPERTY(EditDefaultsOnly)
    UStaticMeshComponent* GunMesh = nullptr;
    UPROPERTY(EditDefaultsOnly)
    USceneComponent* BulletSpawnPoint = nullptr;
};

```

and this is the cpp file.

```
// Fill out your copyright notice in the Description page of Project Settings.

#include "GunBase.h"
#include <Components/StaticMeshComponent.h>
#include <Components/SceneComponent.h>

// Sets default values
AGunBase::AGunBase()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
    RootSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
    RootSceneComponent->SetupAttachment(RootComponent);
    GunMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    GunMesh->SetupAttachment(RootSceneComponent);
    BulletSpawnPoint->SetupAttachment(GunMesh);  //This is the line its complaining about
}

// Called when the game starts or when spawned
void AGunBase::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void AGunBase::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

```

The crash is saying something about an exception access violation, and in particular is referencing line seventeen on the cpp file which has a comment on it. Just in case this means something, I have tried several things to get this code to work, I then builded it, and tried to open the project in unreal again but i always got a crash. thanks.

Edit: I had a function in the header file (pulltrigger its commented out) that was causing me errors but I commented it out and the crash is still occuring.

# Answer
The only code that modifies `BulletSpawnPoint` sets it to `nullptr`, so dereferencing it will crash. You need to initialize it to something, and/or avoid dereferencing it when it is `nullptr`.
> 1 votes

# Answer
For clarification in case anyone has the same problem in the future, OP didn't create the default sub object for the BulletSpawnPoint so the crash was caused when the editor tried to access it.
> 0 votes

---
Tags: unreal-4, crash
---


# Question
Title: How to organize GameObjects into logical groups in a Unity Scene?
Obviously there are a Scene hierarchy, but the problem is that the scene hierarchy was not meant for organizing GameObjects because parent GameObjects affect the transformation of their children.

For example what can one do to select all the decoration GameObjects? Some might be children of non-decoration GameObjects and buried very deep in the scene hierarchy while others might be root GameObjects.

One solution could be to add a Tag, but since Unity restrict you to only one tag per GameObject, that makes the usage of tags pointless as I have different overlapping categories.

Another solution would be to name objects but that is very error prone as a typing mistake will loose my GameObject. Also the team need to memorize possible tokens in the name which allow even more room for human errors.

Another solution would be to add an identifying Component, similar to how tags work in most other applications. But will there be a penalty in build time/runtime in a large project because of the additional Scripts (Components)?

Any other ideas how I can organize my Scene so that I can easily select a logical group of GameObjects from different unrelated parents in the editor Scene or Hierarchical view?

# Answer
> 2 votes
Use marker-components.

The penalty of having a marker-component with no fields and no methods on a lot of objects will in most cases be negligible. But when you are in a situation where every byte matters (and still don't want to use Entities), then you could make that marker component commit suicide on awake:

```
class Decorative : MonoBehaviour {
    private void Awake() {
        Destroy(this);
    }
}

```

This removes just the component, not the object it is on.

# Answer
> 1 votes
Based on Phillip and DMGregory's answer and comment, I found this solution works very well:

Create an Tag Component such as:

```
#if UNITY_EDITOR
using UnityEngine;

namespace AwSim.Tags
{
    [AddComponentMenu("Tags/Decorative")]
    [DisallowMultipleComponent]
    public class Decorative : MonoBehaviour {}
}
#endif

```

Attach it to the Prefabs or GameObjects. You can even add multiple ones like tags.

Because these Components do not implement any of the MonoBehaviour methods, it won't try to do anything at startup except instantiating a useless Component in the editor. However because of the wrapped directive, the Component is removed from the build and won't exist in the production version.

I have tested this in the Editor, Development build and non-development build. All seems to behave as expected with no side effects as far as I can tell. (I have only tested in Windows so far.)

If you need to identify GameObjects at runtime for whatever reason, simply remove the wrapped directive.

When you search for these Components, click on the magnifier icon or press Ctrl+K and type `t:Decorative` and only the Decorative GameObjects will be selected in the Scene. You do not even have to type the full name. Unity will try to match the GameObjects as you type.

As a bonus:

I also added it to the Component Menu in the Unity Editor so that all my Tag Components are nicely grouped together and easy to find in the Unity editor.

I added the `[DisallowMultipleComponent]` to avoid accidental duplicate "tags".

I also added it to a separate namespace to avoid polluting my existing namespace with useless classes. This keeps the intelli-sense clean as well.

---
Tags: unity, gameobject, scene, editors
---


# Question
Title: How to move a player on a sphere surface using Ammo.js and Three,js
I am moving a rigidbody (the character) on the surface of a sphere, like what is described here.

I am facing the following issue that I am having hard time to solve: After moving the character, it starts spinning really slightly around it's Y axis.

As a side note, I am using Ammo.js which is a javascript/webassembly port of Bullet 2.82, but this has no impact on the problem.

To "stick" the player (a dynamic rigidbody with a cylinder shape) to the sphere (a static rigid body with a sphere shape), here is the code, called on each game loop iteration:

```
function applyAttraction() {
    let sphereOrigin = this.body.getWorldTransform().getOrigin();
    let characterOrigin = this._characterEntity.body.getWorldTransform().getOrigin();

    // compute and apply sphere gravity to character body
    let sphereAttractionForce = new ammo.btVector3(
      characterOrigin.x() - sphereOrigin.x(),
      characterOrigin.y() - sphereOrigin.y(),
      characterOrigin.z() - sphereOrigin.z()
    );
    sphereAttractionForce.normalize();
    sphereAttractionForce.op_mul(gravity);
    this._characterEntity.body.applyForce(sphereAttractionForce, ammo.btVector3(0, 0, 0));

    // align character up with sphere origin
    const gravityDirection = bt2ThreeVec3(sphereAttractionForce).normalize().multiplyScalar(-1);

    // extract up axis of character transform basis
    let characterUp = new THREE.Vector3();
    this._characterEntity.graphic.matrixWorld.extractBasis(
      new THREE.Vector3(),
      characterUp,
      new THREE.Vector3()
    );

    // apply rotation to align up with gravity vector
    let verticalAlignmentRotation = new Quaternion()
      .setFromUnitVectors(characterUp, gravityDirection)
      .multiply(bt2ThreeQuat(this._characterEntity.body.getWorldTransform().getRotation()));

    this._characterEntity.body.getWorldTransform().setRotation(three2BtQuat(verticalAlignmentRotation));
  }

```

And to move the character on the sphere (I removed the code dealing with the mouse controlled orientation since it is irrelevant to track down the problem). This code is also called on every game loop iteration:

```
let scalingFactor = 0.02;
    let moveX = inputController.getMoveX();
    let moveZ = inputController.getMoveZ();

    if (moveX === 0 && moveZ === 0) return;

    let movement = new THREE.Vector3(moveX, 0, moveZ).normalize();
    movement.multiplyScalar(scalingFactor);
    let wantedWorldPos = this.graphic.localToWorld(movement);
    this.body
      .getWorldTransform()
      .setOrigin(new ammo.btVector3(wantedWorldPos.x, wantedWorldPos.y, wantedWorldPos.z));

```

In plain (approximative) English, what I am doing:

1. Get the direction from the player position to the center of the sphere
2. Apply a force using that vector: `this._characterEntity.body.applyForce(sphereAttractionForce, ammo.btVector3(0, 0, 0));`
3. Align the player Up with the gravity direction, to do so I:
    1. normalize and "flip" gravity vector direction
    2. extract character up vector and compute the quaternion which give the rotation to align this up vector with the gravity vector
    3. compute the new player orientation by applying quaternion from 3.2 to it's current orientation
4. Apply movement (from keyboard inputs), in details:
    1. get a vector resulting from the requested movement alongside x and z axis
    2. convert this vector from player local basis to world basis: `this.graphic.localToWorld(movement);`
    3. set the new transform origin with this new vector

The project may be seen here (with the spinning issue I am describing). You may need to move a bit on the sphere (with WASD keys).

# Answer
> 1 votes
The character's rigid body is missing angular damping which is causing the spinning to occur.

Calling `setDamping` on the character's rigidbody with value greater than 0 for angularDamping solves the issue.

---
Tags: bullet-physics, three.js
---


title: DX12 - how to update part of a buffer?

text:
# Question
Title: DX12 - how to update part of a buffer?
I'm just getting started in DX12 after a bit of time in Vulkan, I am trying to update a part of a dynamically indexed buffer I'm using to hold mesh transforms.

I'm using the MSFT MiniEngine examples which include wrappers for upload buffers, and am not sure if I can use them to update an existing buffer, or if they're supposed to be the main resource used in place of the "GpuBuffer" in the same engine.

Any specific insight into the use of those classes would be really useful, but more generally, is it possible to update part of a buffer, or will I have to upload a copy of the whole thing?

Obviously a simple example would be brilliant if anyone has one..

# Answer
Right so the answer is very easy it turns out: Using the MiniEngine examples, create a `DynamicUploadBuffer`, map it, copy the data to be transferred into it, then use `WriteBuffer` to update the portion of gpu buffer:

```
    float * buffer = (float*)m_TransformUploadBuffer.Map();
    memcpy(buffer, &trans_mat, 16 * sizeof(float));
    auto index = 1;
    ComputeContext& Ctx = ComputeContext::Begin(L"UploadTest");

    Ctx.WriteBuffer(m_TransformBuffer, index * sizeof(float) * 16, buffer, 16*sizeof(float));
    Ctx.Finish(true);
     m_TransformUploadBuffer.Unmap();

```
> 0 votes

---
Tags: directx, directx12
---


title: Rotating vector3 by a quaternion

text:
# Question
Title: Rotating vector3 by a quaternion
I am attempting to rotate a vector3 by a given quaternion.

I know that this is true

$$ v' = q \cdot v \cdot q^{-1} $$

I know that \\$ q^{-1} \\$ is the inverse which just \\$ \frac {-q} {magnitude(q)} \\$, but how do I map the multiplication of the vector to the quaternion to get back a vector?

I have found that you can treat \\$v\\$ as a matrix, and convert \\$q\\$ and \\$q'\\$ to matrices, and then convert \\$v'\\$ from a matrix to a vector, but this seems a little over the top just to get a vector. Is there a cleaner implementation that I could use?

# Answer
> 54 votes
As Nathan Reed and teodron exposed, the recipe for rotating a vector *v* by a unit-length quaternion *q* is:

1) Create a pure quaternion *p* out of *v*. This simply means adding a fourth coordinate of 0:

$$p = (v\_x, v\_y, v\_z, 0) \Leftrightarrow p = (v, 0)$$

2) Pre-multiply it with *q* and post-multiply it with the conjugate *q\**:

$$p' = q \times p \times q\*$$

3) This will result in another pure quaternion which can be turned back to a vector:

$$v' = (p'\_x, p'\_y, p'\_z)$$

This vector \\$v'\\$ is \\$v\\$ rotated by \\$q\\$.

---

This is working but **far from optimal**. Quaternion multiplications mean tons and tons of operations. I was curious about various implementations such as this one, and decided to find from where those came. Here are my findings.

We can also describe *q* as the combination of a 3-dimensional vector *u* and a scalar *s*:

$$q = (u\_x, u\_y, u\_z, s) \Leftrightarrow q = (u, s)$$

By the rules of quaternion multiplication, and as the conjugate of a unit length quaternion is simply it's inverse, we get:

$$ \begin{align} p' &= qpq\* \\ &= (u, s)(v,0)(-u, s) \\ &= (sv + u \times v, -u \cdot v)(-u, s) \\ &= ((-u \cdot v)(-u) + s(sv + u \times\ v) + (sv + u \times v) \times (-u), \dots) \\ &= ((u \cdot v) u + s^2v + s(u \times v) + sv \times (-u) + (u \times v) \times (-u), \dots) \end{align} $$

The scalar part (ellipses) results in zero, as detailed here. What's interesting is the vector part, AKA our rotated vector *v'*. It can be simplified using some basic vector identities:

$$ \begin{align} v' &= (u \cdot v)u + s^2v + s(u \times v) + s(u \times v) + u \times (u \times v) \\ &= (u \cdot v)u + s^2v + 2s(u \times v) + (u \cdot v)u - (u \cdot u)v \\ &= 2(u \cdot v)u + (s^2 - u \cdot u)v + 2s(u \times v) \end{align} $$

This is now **much more optimal**; two dot products, a cross product and a few extras: around half the operations. Which would give something like that in source code (assuming some generic vector math library):

```
void rotate_vector_by_quaternion(const Vector3& v, const Quaternion& q, Vector3& vprime)
{
    // Extract the vector part of the quaternion
    Vector3 u(q.x, q.y, q.z);

    // Extract the scalar part of the quaternion
    float s = q.w;

    // Do the math
    vprime = 2.0f * dot(u, v) * u
          + (s*s - dot(u, u)) * v
          + 2.0f * s * cross(u, v);
}

```

# Answer
> 7 votes
First of all, q^(-1) is not -q/magnitude(q); it's q\*/(magnitude(q))^2 (q\* is the conjugate; that negates all the components except the real one). Of course, you can leave off the division by the magnitude if all your quaternions are normalized already, which they typically would be in a rotation system.

As for the multiplication with a vector, you just extend the vector to a quaternion by setting a quat's real component to zero and its ijk components to the vector's xyz. Then you do the quaternion multiplications to get v', and then extract the ijk components again. (The real part of v' should always come out zero, plus or minus some floating-point error.)

# Answer
> 5 votes
First observation: The inverse of `q` is not `-q/magnitude(q)`, that is completely wrong. Rotations with quaternions imply that these 4D complex number equivalents have unitary norm, hence lie on the S3 unit sphere in that 4D space. The fact that a quat is unitary means that its norm is `norm(q)^2=q*conjugate(q)=1` and that means that the quat's inverse is its conjugate.

If a unit quaternion is written as `q=(w,x,y,z)` = (cos(t),sin(t)***v**), then its conjugate is `conjugate(q)=(w,-x,-y,-z)`=(cos(t),-sin(t)***v**), where *t* is half of the rotation angle and **v** is the rotation axis (as a unit vector, of course).

When that Hamilton dude decided to play around with complex number equivalents in higher dimensions, he also stumbled upon some nice properties. For example, if you employ a completely pure quaternion `q=(0,x,y,z)` (no scalar part *w* !), you can consider that crap as being a vector (it's actually a quat on what people might call the equator of the S3 sphere, which is an S2 sphere!! - mind bending stuff if we consider how technically impaired the people in the 19th century seem to us eyePhone cowboys nowadays). So Hamilton took that vector in its quat form: `v=(0,x,y,z)` and did a series of experiments considering the geometric properties of quats.. Long story short:

```
INPUT: _v=(x,y,z)_ a random 3D vector to rotate about an __u__ unit axis by an angle of _theta_

OUTPUT: q*(0,_v_)*conjugate(q)

```

where

```
 q = (cos(theta/2), sin(theta/2)*u)
 conjugate(q) = inverse(q) = (cos(theta/2), -sin(theta/2)*u)
 norm(q)=magnitude(q)=|q|=1

```

Observation: the q\*(0,v)\*conj(q) has to be another quat of the form (0,v'). I won't go through all that apparently complicated explanation of why this happens, but if you rotate a pure imaginary quaternion (or a vector in our case!) through this method,you must get a similar kind of object: pure imaginary quat.. and you take its imaginary part as your result. There you have it, the wonderful world of rotations with quaternions in a nut(ty)shell.

**NOTE**: to whomever jumps in with that overused phrase: quats are good because they avoid 'em gimbal lock.. should unlock their imagination first!! Quats are a mere "elegant" mathematical apparatus and can be avoided altogether by using other approaches, the one I find completely geometrically equivalent being the axis angle approach.

**CODE**: the C++ library I fancy is rather simplistic, but has all the matrix, vector and quat operations a 3D graphics experimentalist should need without having to waste more than 15 minutes to learn it.. You can test the things I wrote here using that in 15 minutes if you're not a C++ novice. Good luck!

# Answer
> 2 votes
Here is an alternative way to transform a vector by a quaternion. It is the way MS does it in the xna framework.

```
public static Vector3 Transform(Vector3 value, Quaternion rotation)
{
    Vector3 vector;
    float num12 = rotation.X + rotation.X;
    float num2 = rotation.Y + rotation.Y;
    float num = rotation.Z + rotation.Z;
    float num11 = rotation.W * num12;
    float num10 = rotation.W * num2;
    float num9 = rotation.W * num;
    float num8 = rotation.X * num12;
    float num7 = rotation.X * num2;
    float num6 = rotation.X * num;
    float num5 = rotation.Y * num2;
    float num4 = rotation.Y * num;
    float num3 = rotation.Z * num;
    float num15 = ((value.X * ((1f - num5) - num3)) + (value.Y * (num7 - num9))) + (value.Z * (num6 + num10));
    float num14 = ((value.X * (num7 + num9)) + (value.Y * ((1f - num8) - num3))) + (value.Z * (num4 - num11));
    float num13 = ((value.X * (num6 - num10)) + (value.Y * (num4 + num11))) + (value.Z * ((1f - num8) - num5));
    vector.X = num15;
    vector.Y = num14;
    vector.Z = num13;
    return vector;
}

```

# Answer
> 0 votes
In C using Hamilton products. The rotate function takes a 3d vector for the point you want to rotate and the axis of rotation, and then the output is another 3d vector that you pass in to be modified.

hamilton\_product function just does the operations defined by this wikipedia section: https://en.wikipedia.org/wiki/Quaternion#Hamilton\_product

void hamilton_product(const float* q, const float* r, float *output){
  output[0] = (q[0] * r[0]) - (q[1] * r[1]) - (q[2] * r[2]) - (q[3] * r[3]);
  output[1] = (q[0] * r[1]) + (q[1] * r[0]) + (q[2] * r[3]) - (q[3] * r[2]);
  output[2] = (q[0] * r[2]) - (q[1] * r[3]) + (q[2] * r[0]) + (q[3] * r[1]);
  output[3] = (q[0] * r[3]) + (q[1] * r[2]) - (q[2] * r[1]) + (q[3] * r[0]);
}

void make_quaternion(const float* axis, const float theta, float *output){
  float sin_theta = sin(theta);

  output[0] = cos(theta);
  output[1] = sin_theta * axis[0];
  output[2] = sin_theta * axis[1];
  output[3] = sin_theta * axis[2];
}

void rotate(const float* point, const float* axis, const float theta, float *output){
  static float q[4];
  static float q_conj[4];
  static float o4d[4];
  static float p[4];
  static float inter[4];
  make_quaternion(axis, theta/2, q);

  memcpy(q_conj, q, sizeof(q_conj));
  q_conj[1] = -q[1];
  q_conj[2] = -q[2];
  q_conj[3] = -q[3];

  p[0] = 0.0F;
  memcpy(&p[1], point, 3*sizeof(float));

  hamilton_product(q, p, o4d);

  memcpy(inter, o4d, sizeof(o4d));

  hamilton_product(inter, q_conj, o4d);

  memcpy(output, &o4d[1], 3*sizeof(float));
}
```
</code></pre>

# Answer
> -1 votes
I tried to work this out by hand, and came up with the following equation/method:

```
// inside quaterion class
// quaternion defined as (r, i, j, k)
Vector3 rotateVector(const Vector3 & _V)const{
    Vector3 vec();   // any constructor will do
    vec.x = 2*(r*_V.z*j + i*_V.z*k - r*_V.y*k + i*_V.y*j) + _V.x*(r*r + i*i - j*j - k*k);
    vec.y = 2*(r*_V.x*k + i*_V.x*j - r*_V.z*i + j*_V.z*k) + _V.y*(r*r - i*i + j*j - k*k);
    vec.z = 2*(r*_V.y*i - r*_V.x*j + i*_V.x*k + j*_V.y*k) + _V.z*(r*r - i*i - j*j + k*k);
    return vec;
}

```

I would appreciate if someone would look over mt deriviation I used http://pastebin.com/8QHQqGbv I would suggest to copy to a text editor that supports side scrolling

in my notation I used q^(-1) to mean conjugate, and not inverse, and different identifiers, but I hope that it is follow-able. I think that the majority is right especially where on proving the real portion of the vector would disappear.

---
Tags: c++, quaternion
---


title: How to see real world size in blender

text:
# Question
Title: How to see real world size in blender
I want to make a .stl file to be 3d printed through blender, but I don't know how I would see the real size. Does anyone have any solutions? Also, if you turn on smooth shading, will it actually be smooth IRL or just the shading?

# Answer
> 1 votes
Blender uses meters as its default unit scale. If you add in a cube, it will give you the option to change its size in the popup window. Set the cube to the desired scale and match the scale of your object to it or set the cube to 1 m and use it to determine the scale of your grid lines.

As for smooth shading, that just turns on normal averaging on the vertices. It does not add any detail to the geometry. The smoothness is an optical illusion from the even transition of light across the face. If you plan on printing, be sure to turn smooth shading off so WYSIWYG.

---
Tags: 3d, blender
---


# Question
Title: Is it possible to somehow change the collider points to match sprites during the animation in Unity?
Is it possible to somehow change the collider points to match sprites during the animation in Unity?

I am using the Unity built in animtion recording feature. I would like to change the points of some of my colliders as animation goes, while at the same time I am changing the respective sprites. I was not able to find any solutions so far.

Any ideas how I could do that?

I have a few attempts to overcome the problem.

1. Create a few game objects with the different preset points for the colliders. The solution will work. But it is crazy hard to develop and maintain resources wise. I will have to spend an immense amount of time creating a separate game object with a collider for each frame. And also the maintenance will be very lame. Because I will need to add a wrapper around all the places where I access collider. So that the wrapper would return the currently enabled collider.
2. I can buy the 2DColliderGen. But I do not want to spend money on that. And also it is not completely what I am looking for, because even with it I will have significant difficulties developing my animations, maintaining my game and extending it.

# Answer
It seems that there is no way as of right now to achieve that easily in Unity.

So, in my case I was able to get going with the following:

* for the head I just use the -1 x scale for the collider object. That makes the collider match my mirrored head sprite.
* for the legs I just scale down the collider. That allows me to get a very nice precision.

The solution above does not present any technical debt and is easy to implement with the default animation system in Unity.
> 0 votes

---
Tags: unity, 2d, animation, collider
---


# Question
Title: Applying velocity to parent that ignores children's mass not working
I am making a VR data visualisation app in Unity and I have a parent with many children (just some primitive cubes) that I can toss around the scene by just setting the parent's rigidbody to the same velocity as my tracked VR controller.

```
Rigidbody rb = GetComponent<Rigidbody>();
Vector3 controllerVelocity = Player.instance.rightHand.GetTrackedObjectVelocity(); // how I ref the controller velocity in SteamVR
rb.velocity = controllerVelocity * 2f; // the 2f is just to speed up the velocity

```

The above code works fine, but the problem is I think the scale of the children objects, which can be adjusted by the player, is affecting the velocity the parent moves at. Or maybe just when the children are very large...the controller velocity is comparatively too slow? Basically I need this to not be the case; I want the parent's rigidbody to move at roughly the same velocity no matter the children's scales/masses.

So to achieve that I thought to use Rigidbody.AddForce but it doesn't seem to be making any difference i.e. larger children are still moving slower. Here is what I have so far:

```
Rigidbody rb = GetComponent<Rigidbody>();
Vector3 controllerVelocity = Player.instance.rightHand.GetTrackedObjectVelocity();
rb.AddForce(controllerVelocity  * 2f, ForceMode.VelocityChange);

```

I also tried ForceMode.Acceleration but then nothing moved at all? Am I using AddForce incorrectly? Or do I just need a scaling multiplier based on the size of the children? Any help is welcome.

# Answer
> 0 votes
Not ideal, but was able to mimic my intended result by doing the following:

```
float parentMagnitude = transform.lossyScale.magnitude;
float thrustAdjuster = parentMagnitude * 5f;
Vector3 controllerVelocity = Player.instance.rightHand.GetTrackedObjectVelocity();
rb.velocity = controllerVelocity * thrustAdjuster;

```

---
Tags: unity, rigidbody, collider
---


title: OBJ file has more vertices than normals

text:
# Question
Title: OBJ file has more vertices than normals
Here is a Pastebin of my OBJ file created using Solidworks 3D https://pastebin.com/6MgQBF8J

I don't understand how the number of vertices (645) can be larger than the number of normals (306)

I understand that some vertices have the same exact coordinates, but how is a programmer supposed to know which normals correspond to which vertices?

Since there are no indexes to map normals to vertices, do I need to get rid of the duplicates first until the number of normals and vertices is equal? But then why are the duplicates there in the first place?

Or do I need to create normals equal to zero for the remaining vertices?

# Answer
> 1 votes
See this page for a great analysis of the OBJ format. In an OBJ file, vertex normals are associated with vertices where the faces are defined. Faces are defined along the bottom of the file, on lines starting with `f`, e.g.

```
f 632/996/280 638/997/280 637/971/280

```

Each triplet consists of a vertex index, texture vertex index, and vertex normal index. So that answers how normals are mapped to vertices. So this example face has three vertices (a triangle).

The first part of your question I'm not 100% certain about. Since the vertex normals and vertices are referenced by index, we could reduce the file size by merging any duplicates into a single index. So for example, if this vertex normal appeared in the file 5 times

```
vn -0.66051400 -0.44590101 -0.60406399

```

we could prune the 4 duplicates and remap their indices to the first index. However, your OBJ file does still contain some duplicate vertex normals, so either duplicates are not pruned at all, or SolidWorks just doesn't do it thoroughly.

# Answer
> 0 votes
A .obj file has lists of vertices and normal that have an implicit 1 based index. The first item you read in is 1, the second is 2, etc.

Further down in the file, you will see a list of faces that look like F 1/1/1 2/2/2 3/3/3

Each tuple of numbers represents the index of the position/uv tex coords/normal that forms the information for that vertex. When you take all three tuples together, you get a single triangle. You will usually end up with far more information than is stored in the file because obj compresses duplicates.

---
Tags: obj
---


# Question
Title: "Update cannot be an iterator block" when trying to wait for jump to finish
As of now, I'm getting a C# error (CS1624) stating that:

> The body of PlayerMovement.Update() cannot be an iterator block because void is not an iterator interface type.

The error is within the `void Update section`. I believe it started when I added lines 34 - 37, the second "if" clause.

Here's the code:

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

public class PlayerMovement : MonoBehaviour
{

    Animator m_Animator;
    bool m_Jump;

    public CharacterController2D controller;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;

    void Start()
    {
        m_Animator = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if (Input.GetButtonDown("Jump"))
        {
            jump = true;
            m_Animator.SetBool("Jump", true);
        }

        // These are lines 34-37 that cause the error, I think.
        if (m_Animator.GetBool("Jump") == true)
        {
            yield return new WaitForSeconds(3);
            m_Animator.SetBool("Jump", false);
        }
    }

    void FixedUpdate()
    {
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
        jump = false;
    }
}

```

# Answer
When you want a method that can pause its execution and resume later in Unity, that's called a Coroutine, and it needs to be set up in a specific way. The return type has to be `IEnumerator`, not `void`.

That's why the compiler complains when you try to put a `yield return` statement inside a `void Update` \- "`void`" is not a type that can be used as an iterator, which is what Unity's coroutines are built on.

If you change the return type to `IEnumerator`, Unity will tell you that the `Update` method is forbidden from being used as a coroutine. But that's OK, we can start our own named whatever we like.

Here's a version of your script with working syntax:

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

public class PlayerMovement : MonoBehaviour
{

    Animator m_Animator;
    bool m_Jump;

    public CharacterController2D controller;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;

    void Start()
    {
        m_Animator = gameObject.GetComponent<Animator>();

        // Start our coroutine when the MonoBehaviour activates.
        StartCoroutine(JumpPoll());
    }

    IEnumerator JumpPoll()
    {
        while(true) {
            // If you don't want to lock horizontal input while jumping,
            // then move this line into FixedUpdate. It's OK to read axes there.
            horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

            if (Input.GetButtonDown("Jump"))
            {
                jump = true;
                m_Animator.SetBool("Jump", true);

                // Pause this loop for 3 seconds while the rest of the game proceeds.
                yield return new WaitForSeconds(3);

                m_Animator.SetBool("Jump", false);
            }
            // Let the game run one frame,
            // and resume next frame just like Update() does.
            yield return null;
        }
    }

    void FixedUpdate()
    {
        // Time.deltaTime automatically returns fixedDeltaTime
        // when accessed from FixedUpdate, so it's good to just use that
        // (less risk of errors when moving code or calling it from other places).
        controller.Move(horizontalMove * Time.deltaTime, false, jump);
        jump = false;
    }
}

```
> 1 votes

# Answer
Quick solution but for other wait operations you might want to use a `Coroutine`. `Invoke` is not a real timer or counter but the second parameter allows you to specify the time amount when the call should be executed. In this case the function `ResetJump` will run 3 seconds later and reset your jump.

```
void Update() {
    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
    if ((Input.GetButtonDown("Jump")) && (jump == false))
    {
        jump = true;
        m_Animator.SetBool("Jump", true);
        Invoke("ResetJump", 3f);
    }
}

private void ResetJump() {
    jump = false;
    m_Animator.SetBool("Jump", false);
}

```
> 0 votes

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


# Question
Title: Instantiate prefab on specified position of GameObject on scene
I have a room that I want to connect to a staircase. Both the room and the stairs have the following parameters:

I need to "magnet" the "Room Exit" position of the room (start room) to the "Room Entry" staircase. The staircase itself, I create through Instantiate

How can i do this?

# Answer
If I understand you correctly, you have two objects that contain entry and exit points. The entry/exit points are each marked by the location of a specific child object transform inside those parents. You want to find a position to place one of these parent objects so its entry child exactly matches the position of the other parent object's exit child.

If so, you can do that like this:

```
void SnapParentToAnchor(Transform anchor, Transform parentToMove, Transform childToAlign) {
    // Get the position in the world of the fixed child we want to align to.
    Vector3 worldPosition = anchor.position;

    // Get the world space offset of the matching child from its parent.
    var offset = parentToMove.TransformVector(childToAlign.localPosition);

    // Form a world position for the parent that will put this offset exactly at our anchor.
    parent.position = worldPosition - offset;
}

```

You can use this to fix-up the position of the parent after you've instantiated it with the rotation and scale you want.

Or, if you're not rotating/scaling these objects, you could change this method to return the `Vector3 position = worldPosition - offset` to use. Then call it with the prefab parent/child to get that vector, and pass it to `Instantiate(prefab, position, rotation)` to instantiate it in-place in one go.
> 0 votes

---
Tags: unity, transformation
---


title: Main Camera re-sizing in 2d

text:
# Question
Title: Main Camera re-sizing in 2d
My UI :

An UI from YouTube video :

Look my camera's size is 10 and his camera's size is only 5. But, my camera's width is larger than height. If you look at scale (x,y,z)=(1,1,1). I tried to change them. But, nothing changes.I tried to change `ViewPort Rect` then, I am able to change the size of Main Camera. But, look at following image. His `ViewPort Rect` is 1 by 1 mine also. But, we have differences of width and height.

How to fix it?

# Answer
While D.Kallan focuses with his answer on how to make it closer to Brackeys', this answer focuses more on if you actually should do that.

Since you are new to GameDev, I would guess for now most of your projects are for yourself and the learning experience. Instead of following the tutorial to the letter, you should make the game look great on your own platform. Since the topic of handling different resolutions, fit to the screen and similar can be quite confusing (even more so when you try to learn the basics), you should fix your game to the resolution you are actually using yourself.

That means, if you plan to make a small mobile game, use a fixed aspect and enter your own mobile resolution there. If it is for pc, use your screen resolution under which you plan to play the game later. This saves you the trouble that while the game will work and looks similar to the tutorial in the editor, it might look totally different when you want to play your own game or show it to friends. Once the game is actually done and looks great on your own hardware, you can learn about the topics on how to make it look great for everybody else.

You can set a fixed resolution in the game tab.
> 1 votes

# Answer
I have noticed that when your camera is on `Free Aspect`, the size changes with the size of your `game window`.

If you compare the differences between your UI and Brackeys' UI, you see that your game window is wider than his, and a little smaller vertically.

**Try resizing the game window to match his** and your camera should then match about the same ratio as Brackeys' has.
> 1 votes

---
Tags: unity, 2d, camera
---


# Question
Title: Scale / NonUniformScale is not applied to entity
I'm just learning the new Unity ecs and trying to change the size (scale) of an entity. Everything works fine, I can change the rotation, the position *but not the scale*.

I'm wondering why. I did various tutorials, I tried Scale, NonUniformScale, LocalToWorld, CompositScale but nothing works. Maybe some of the methods are deprecated.

Here is what I have tried so far.

I have multiple prefabs (planes) which are spawned correctly and each of them having a transform component.

Now I want to change the scaling of all the planes. For that I use a JobComponentSystem. In the following pice of code the rotation works fine, but not the scaling.

I tried LocalToWorld.

```
public void Execute(ref Rotation rotation, ref LocalToWorld scale) {
            rotation.Value = math.mul(rotation.Value, quaternion.RotateZ(math.radians(0)));
            scale.Value = float4x4.Scale(2, 4, 5);
        }

```

I tried NonUniformScale

```
public void Execute(ref Rotation rotation, ref NonUniformScale scale) {
            rotation.Value = math.mul(rotation.Value, quaternion.RotateZ(math.radians(0)));
            scale.Value = new float3(2, 1, 4);
        }

```

I tried Scale.

```
public void Execute(ref Rotation rotation, ref Scale scale) {
            rotation.Value = math.mul(rotation.Value, quaternion.RotateZ(math.radians(0)));
            scale.Value = 5;
        }

```

None of these is working. What did I wrong (the scale just stays at 10,1,10) or what is the current propper way of doing that?

# Answer
> -1 votes
```
public void Execute(ref Rotation rotation, ref CompositeScale scale) {
        rotation.Value = math.mul(rotation.Value, quaternion.RotateZ(math.radians(0)));
        scale.Value = float4x4.Scale(1, 2, 1);
    }

```

---
Tags: unity, c#, entity-component-system, unity-dots
---


# Question
Title: Find position in arc depending on the direction of the agent
So what I am trying to do is to find a random point on the (green") arc around the enemy:

Sorry for the bad drawing but

* Red (no go)
* Green ( Points the allied can go to)

I know that unity has the following function:

```
Radius = 5;
_randomDirection = (Random.insideUnitCircle * _target.position).normalized;
Vector3 finalPosition = _target + _randomDirection + Radius;

```

However, this is for a full circle. How can I achieve the closest half circle?

# Answer
> 3 votes
Check if the point you get is on the far half-circle, and if it is, mirror it.

```
Radius = 5;
_randomDirection = (Vector3)(Random.insideUnitCircle).normalized;

Vector3 toTarget = _target.position - _source.position;
if (Vector3.Dot(toTarget, _randomDirection) > 0f) {
    _randomDirection = Vector3.Reflect(_randomDirection, toTarget);
}

Vector3 finalPosition = _target.position + _randomDirection * Radius;

```

You can also create this vector from scratch using a random angle:

```
Vector2 fromTarget = (_source.position - _target.position).normalized;
Vector2 perpendicular = new Vector2(-fromTarget.y, fromTarget.x);

float angle = Random.Range(0, Mathf.PI);

Vector2 offset = fromTarget * Mathf.Sin(angle) + perpendicular * Mathf.Cos(angle);

Vector3 finalPosition = _target.position + (Vector3)(offset * Radius);

```

---
Tags: unity, vector
---


# Question
Title: Find projecting triangle for UV mapping in RuneScape model format
I am using an old Runescape model format, also used by Thief and Quake. In this format, instead of specifying UV coordinates for each vertex ABC, we specify a second trio of vertices PMN. Those vertices are then used to project UV texture coordinates onto ABC.

Some previous Q&A explains this projection algorithm and how to reverse it.

I have a mesh with UVs that I want to save in this format. To do that, I want to find a trio of vertices PMN for each triangle ABC that reproduce the correct UVs.

These PMN vertices are chosen from the collection of vertices already in my mesh.

I could search every possible ordered triangle in my mesh, but that scales as \\$O(n^3)\\$ and would be impractical for meshes with high vertex counts.

How can I more efficiently find a PMN triangle that produces my desired UV coordinates on each triangle ABC?

# Answer
First, it's helpful to develop some geometric intuition about how this UV projection algorithm works. We define a 2D UV space using the \\$PMN\\$ points to form our origin and basis vectors:

* Point \\$P\\$ corresponds to (u, v) = (0, 0)
* Point \\$M\\$ corresponds to (u, v) = (1, 0)
* Point \\$N\\$ corresponds to (u, v) = (0, 1)

Then we project that UV space along the normal perpendicular to the plane of \\$\triangle PMN\\$, onto \\$\triangle ABC\\$.

My answer to the earlier question shows how to find a particular choice of \\$\triangle PMN\\$ in the plane of \\$\triangle ABC\\$ itself. Let's call them \\$P\_0\\$, \\$M\_0\\$, \\$N\_0\\$. We can use this as the starting point of our search for other \\$\triangle PMN\\$ candidates.

First, check a small sphere or box around \\$P\_0\\$, \\$M\_0\\$, and \\$N\_0\\$. If you already have a vertex in all three spots (maybe even the vertices of \\$\triangle ABC\\$ itself) then we can just use those and skip any wider search.

If we don't have a good candidate there, then we can look at each candidate point P that's *not* in \\$\triangle ABC\\$'s plane.

For each such candidate \\$P\\$, take the vector \\$P - P\_0\\$. This forms our projection axis, the normal to the plane of \\$\triangle PMN\\$. We can use that to find the positions where \\$M\\$ and \\$N\\$ would need to be:

$$\begin{align} M = M\_0 + t (P - P\_0) \quad \text{such that} \quad(M - P) \cdot (P - P\_0) &= 0\\ (M\_0 + t(P - P\_0)) \cdot (P - P\_0) &= 0\\ M\_0 \cdot (P - P\_0) + t (P - P\_0)^2 &= 0\\ t (P - P\_0)^2 &= M\_0 \cdot (P\_0 - P)\\ t &= \frac {M\_0 \cdot (P\_0 - P)}{(P\_0 - P)^2} \end{align}$$

...and likewise for \\$N\\$.

Check a small sphere or box around these points to see if you have a suitable vertex in your mesh. If both check out, then you have a candidate \\$\triangle PMN\\$.

If you find multiple candidates, you can score them by computing the UVs each candidate triangle assigns to \\$A\\$, \\$B\\$, and \\$C\\$, and summing the squared error. Choose the candidate with the least error.

If you continue this search to check all candidate \\$P\\$ vertices in your mesh, then it scales as \\$O(n)\\$, a major improvement over \\$O(n^3)\\$ checking every possible triangle.

And you can restrict this search to a subset of promising candidates \\$P\\$ for further savings. Ideally we want to find a \\$\triangle PMN\\$ that's reasonably close to \\$\triangle ABC\\$ \- otherwise when we do the subtractions we could get catastrophic cancellation that lowers our precision. And we'd like its plane to be roughly parallel to \\$\triangle ABC\\$, so we don't lose precision to a shallow oblique projection.

With those two constraints in mind, searching a double-cone of restricted height, with its point at \\$P\_0\\$ and its axis perpendicular to the plane containing \\$\triangle ABC\\$ should cover the best candidates. You can adjust the cone's angle and maximum height to widen your search to less-promising candidates if your initial pool lacks good matches.
> 0 votes

---
Tags: geometry, projection, linear-algebra, uv-mapping
---


# Question
Title: Is it legal to use Creative Commons art in a commercial game?
I would like to know if the following situation would be legal.

Let's say I take some pictures on wikipedia, that are licensed under **CC-BY-SA** license. Then I would like to photoshop them, and use it as art in a (perhaps commercial) game.

According to the Creative Commons licence, it is legal to use the content "for any purpose, even commercially". So I was thinking about creating a web page where I would attribute each picture to the original creator, and publish the photoshoped picture under the same license (even if it would be almost useless for anyone).

Would it be legal? Or would I need to publish the entire game under creative commons license?

# Answer
http://creativecommons.org/licenses/by-sa/4.0/ according to this website you can use it commercially but it needs to have same license, see the sharealike. i don't know about game but website will be i think totally legal, if you of course upload edited image with cc license

but please ask someone else too. I'm not expert in licenses
> 2 votes

# Answer
Anything derived from using a CC-BY-SA licensed work should be distributed under the same license. This includes the edited image and the work it is used in. Since you are mixing it with other things (other images, music, code) to create a new work (a game), the new work should carry the same license.

In short, if you use a CC-BY-SA licensed image to make a video game, the game can be commercial but it should also carry the same license, which means its source and other materials should also be available for others to use under the same terms.

Since video games include many different materials, licensing everything in it CC-BY-SA can be complicated. For example you may not have the rights to redistribute the music. It is better to use custom made, CC-BY, or public domain works when making video games.
> 8 votes

# Answer
**Collection vs derived work**

TL;DR: I'm not sure, but this is a distinction that might be worth looking into.

https://academia.stackexchange.com/questions/48375/using-images-with-cc-by-sa-license-in-slides-or-a-thesis/48382#48382 is for the image in book/thesis, which I believe is analogous for the game case.

In CC By-SA 3.0, there was clear distinction between "derived" and "collective" work, and it was explicitly mentioned that if you include an image in a book, the book is a "collective work", not derived, and does not need to be CC By-SA. So the image in game might be analogous.

> "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License.

This was somewhat tested in US court for an Atlas at Drauglis v. Kappa Map Group, LLC where a 2.0 image was used as a cover of an Atlas, with attribution on the back cover, and no infringement was found.

However, it is hard for me to be sure if the "a single image in book/game case" is actually a collection or not. Can a collection have a single item? Are the icons of your UI a collection? Intuitively it does not feel like it, since their main goal is not to showcase the items, but rather to integrate into your work.

Also within a game, it might not be feasible to have a clear attribution for every image within the media itself, which makes it feel even less like a collection.

In 4.0 the term "collective work" was dropped, and things became even less clear, although most people are guessing that hasn't changed, although I could not find clear evidence. https://opensource.stackexchange.com/questions/7022/using-cc-by-sa-music-in-a-podcast/7036#7036 suggests that this distinction in 4.0 is simply delegated to your local law, or in other words, as a lawyer, and kind of reduces the usefulness of a license in the first place. The collective work wiki page has comments on it for several countries.

Related questions:
> 1 votes

---
Tags: legal, art
---


# Question
Title: OpenGL GLSL ES 3.10 - Referencing a uniform variable, causes the vertex shader to not draw anything
I have this project, that has a default shader, that just draws models and textures. Recently I decided to add a second shader that does a fancy effect, and is used only on some of the objects drawn.

After compiling the project for Linux or Windows, it all works as expected. When compiling the project to Android, only on specific devices, the new shader doesn't work, while on other devices I tried, it all works.

## My shaders

Below is my default vertex shader specifically made for Android devices, this one works on all devices and draws everything without any editing or effect. As far as I understand, the fragment shaders work, so I'll omit them.

```
    #version 310 es

    in vec4 position;
    in vec3 colour;
    in vec2 texCoord;

    uniform mat4 matrix;
    uniform mat4 matrixProjection;

    out vec2 outTexCoord;
    out vec4 outColour;

    void main() {
            gl_Position = matrixProjection *matrix *position;
            outTexCoord  = texCoord;
            outColour  = vec4(colour.rgb, 1);
    }

```

I hope this looks fairly straight-forward. `matrixProjection` is the projection matrix, and `matrix` is the model-view matrix. They both work as expected and I'm able to render a whole scene without issue.

Now here is a simplified version of my new shader:

```
    #version 310 es

    in vec4 position;
    in vec3 colour;
    in vec2 texCoord;

    uniform mat4 matrix;
    uniform mat4 matrixProjection;
    uniform float animationCurrent;

    out vec2 outTexCoord;
    out vec4 outColour;

    void main() {
            gl_Position = matrixProjection *matrix *position;

            if (animationCurrent > 0.0) {
                    gl_Position.y += 5.0;
            }

            outColour = vec4(colour.rgb, 1.0);
            outTexCoord  = texCoord;
    }

```

The only difference of the new shader is the new uniform `animationCurrent`, and an extra `if` statement that will modify the `gl_Position.y` of some vertices. Any object that is using this shader, is not drawn at all on the screen on some devices.

## What I've tried

From the new shader, if I remove the entire `if` statement, it all works and it displays objects as-is. If I replace the `if` statement with `if (true)` it still works, but it just displays all vertices of objects drawn with it slightly higher. If I replace it with `if (false)` it still works as expected.

So for some reason, just referencing `animationCurrent` causes the object to not be drawn.

I also tried replacing the `if` statement with `if (matrix[0][0] > 0.0)` and it still draws the object, it looks like there's something specifically wrong with `animationCurrent`. I tried adding another matrix uniform variable, and set its value the same way as I do `matrix`, but it wouldn't draw the object either.

This should mean that the value of `animationCurrent` is not relevant, and the fact that it's a `uniform float` doesn't matter either.

## Hardware

The problem occurs on an android phone with this hardware:

```
Device: Moto E (4) Plus - 7.1.1
Vendor graphic card: ARM
Renderer: Mali-T720
Version OpenGL: OpenGL ES 3.1 v1.r12p1-01alp0.62f282720426ab7712f1c6b996a6dc82
Version GLSL: OpenGL ES GLSL ES 3.10

```

And this android tablet with similar hardware:

```
Device: Kindle Fire 8
Vendor graphic card: ARM
Renderer: Mali-T720
Version GL: OpenGL ES 3.1 v1.r26p0-01rel0.526d936ea9da20486773a9aaceecd920
Version GLSL: OpenGL ES GLSL ES 3.10

```

This is an android tablet where everything works as expected:

```
Device: Lenovo TB-X505F - 10
Vendor graphic card: Qualcomm
Renderer: Adreno (TM) 504
Version GL: OpenGL ES 3.2 V@415.0 (GIT@f345350, I0760943699, 1580221225) (Date:01/28/20)
Version GLSL: OpenGL ES GLSL ES 3.20

```

And here is a slightly older device that works. I've modified the shader a bit to support an older glsl version, but the idea is the same:

```
Device: Kindle Fire 7
Vendor graphic card: ARM
Renderer: Mali-450 MP
Version GL: OpenGL ES 2.0
Version GLSL: OpenGL ES GLSL ES 1.00

```

## Question

My primary goal, is to understand what is causing this. Have I missed something very obvious? Is this a very edge-case bug related to the hardware?

I'm still learning how to support different devices with different versions of glsl, so it's very likely I've missed something.

Any information you have, let me know. I'm willing to try a few things on different devices to find more about this issue.

# Answer
> 0 votes
I've just found what the problem is, and the workaround for it.

On those specific devices, it seems that declaring the uniforms in a specific order matters. I'm not sure if that's a bug with `Mali-T720` (since both devices use it) or with GLSL 3.10, as I don't have enough devices to test this.

My solution was changing from this:

```
uniform mat4 matrix;
uniform mat4 matrixProjection;
uniform float animationCurrent;

```

To this:

```
uniform float animationCurrent;
uniform mat4 matrix;
uniform mat4 matrixProjection;

```

The shader compiles successfully and renders all the special effects modified by `animationCurrent`. I don't know what's the order of all different uniform types, but hopefully this can help someone having a similar issue in the future.

If anybody knows why this happens, and if it's indeed a bug with the hardware, or something mentioned by a specific version of OpenGL, let me know, as I'd still like to know why this behaves this way.

---
Tags: opengl, shaders, opengl-es, hardware, opengl-es3
---


title: Weird colour effects in Unity build

text:
# Question
Title: Weird colour effects in Unity build
I have a project where I am getting a very weird thing in the build. Normally, the scene is working fine but some of the objects are showing like this. For example, the tracks or some of the trees.

# Answer
> 0 votes
After applying Compression to some heavy texture. The problem has no more. I have applied normal compression to some of the heavy textures.

---
Tags: unity, build
---


# Question
Title: How can I make the player "look" to the mouse direction? (Pygame / 2D)
Here's my code:

```
import sys
import pygame
pygame.init()

screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
running = True

class Actor:

    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.surface = pygame.image.load("GFX/player.png")
        self.rotated_surface = self.surface.copy()
        self.rect = self.surface.get_rect()

class Player(Actor):

    def __init__(self):
        Actor.__init__(self, 0, 0, 32, 32)
        self.directions = [False, False, False, False]
        self.speed = 0.1

    def rotate(self, angle):
        rot_image = pygame.transform.rotozoom(self.surface, angle, 1)
        rot_rect = self.rect.copy()
        rot_rect.center = rot_image.get_rect().center
        self.rotated_surface = rot_image

    def move(self):
        if self.directions[0]:
            self.y -= self.speed
        if self.directions[1]:
            self.y += self.speed
        if self.directions[2]:
            self.x -= self.speed
        if self.directions[3]:
            self.x += self.speed

    def draw(self):
        screen.blit(self.rotated_surface, (self.x, self.y))

player = Player()

def redraw():
    screen.fill((75, 0, 0))
    player.draw()
    player.move()
    pygame.display.flip()

while (running):
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            sys.exit()
        elif e.type == pygame.KEYDOWN:
            if e.key == pygame.K_ESCAPE:
                sys.exit()
            if e.key == pygame.K_w:
                player.directions[0] = True
            if e.key == pygame.K_s:
                player.directions[1] = True
            if e.key == pygame.K_a:
                player.directions[2] = True
            if e.key == pygame.K_d:
                player.directions[3] = True
        elif e.type == pygame.KEYUP:
            if e.key == pygame.K_w:
                player.directions[0] = False
            if e.key == pygame.K_s:
                player.directions[1] = False
            if e.key == pygame.K_a:
                player.directions[2] = False
            if e.key == pygame.K_d:
                player.directions[3] = False
        elif e.type == pygame.MOUSEMOTION:
            mouse_x = pygame.mouse.get_pos()[0]
            mouse_y = pygame.mouse.get_pos()[1]
            angle = math.atan2(mouse_y - player.y, mouse_x - player.x)
            angle = angle * (180 / math.pi)
            player.rotate(angle)

    redraw()

```

Here's the image:

The blue arrow represents the "weapon" / "eyes" of the shooter, and the green arrow represents the mouse cursor. How can I use the transform module to rotate the image "in the direction" of the mouse cursor?

# Answer
> 8 votes
First you need to calculate the vector pointing from your player to the current mouse position. This can be done by subtracting the player's position with the mouse's position:

```
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - self.x, mouse_y - self.y

```

Then calculate the angle:

```
angle = math.atan2(rel_y, rel_x)

```

This will calculate the angle in radians while the `pygame.transform.rotate(surface, angle)`takes the angle in degree. It will also calculate the angle in the other direction (counter-clockwise) so you need to negate the result. If the image starts at the wrong direction just add/subtract 90 or 180 until it's right:

```
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)

```

After rotating, you need to reposition your rect so that the image remains in the same spot. Rotating images changes it size which makes it look slightly out of position each rotation. I usually position it so its center is consistent.

```
self.image = pygame.transform.rotate(self.original_image, int(angle))
self.rect = self.image.get_rect(center=self.position)

```

Notice that I rotate an attribute named `self.original_image`. When applying rotation to an image it becomes slightly distorted. Doing this several times will eventually make your image unrecognizable. So always have a reference to the original image that's unaltered.

Also, naming your attribute `self.image` instead of `self.surface` and inheriting from `pygame.sprite.Sprite` allows you to use many convenient functions described in the `pygame.sprite` module.

The full code:

```
import math

def rotate(self):
    mouse_x, mouse_y = pygame.mouse.get_pos()
    rel_x, rel_y = mouse_x - self.x, mouse_y - self.y
    angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
    self.image = pygame.transform.rotate(self.original_image, int(angle))
    self.rect = self.image.get_rect(center=self.position)

```

# Answer
> 1 votes
I don't have experience with python, but try: `atan2(mouseY, mouseX)` -and yes, thats (y, x) not (x,y).

# Answer
> 0 votes
You can also use vectors to get the angle. The `pygame.math.Vector2` class has a `.as_polar` method which returns the polar coordinates, the radius (distance) and the angle to the target.

```
import pygame as pg
from pygame.math import Vector2

class Player(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((50, 30), pg.SRCALPHA)
        pg.draw.polygon(self.image, pg.Color('steelblue2'),
                        [(0, 0), (50, 15), (0, 30)])
        self.orig_image = self.image  # Store a reference to the original.
        self.rect = self.image.get_rect(center=pos)
        self.pos = Vector2(pos)

    def update(self):
        self.rotate()

    def rotate(self):
        # The vector to the target (the mouse position).
        direction = pg.mouse.get_pos() - self.pos
        # .as_polar gives you the polar coordinates of the vector,
        # i.e. the radius (distance to the target) and the angle.
        radius, angle = direction.as_polar()
        # Rotate the image by the negative angle (y-axis in pygame is flipped).
        self.image = pg.transform.rotate(self.orig_image, -angle)
        # Create a new rect with the center of the old rect.
        self.rect = self.image.get_rect(center=self.rect.center)

pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group(Player((300, 220)))
done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    all_sprites.update()
    screen.fill((30, 30, 30))
    all_sprites.draw(screen)

    pg.display.flip()
    clock.tick(30)

```

# Answer
> 0 votes
You have to compute the angle of the vector from the player to the mouse. get the mouse position by `pygame.mouse.get_pos()` and the rectangle (`pygame.Rect`) around the player (`self.rect` ):

```
mx, my = pygame.mouse.get_pos()
player_rect = self.rect

```

Calculate the vector from the player to the mouse and compute the angle of vector by `math.atan2`. The y-axis needs to be reversed (`-dy`) as the y-axis is generally pointing up, but in the PyGame coordinate system the y-axis is pointing down.

```
dx, dy = mx - player_rect.centerx, player_rect.centery - my
angle = math.degrees(math.atan2(-dy, dx)) - correction_angle

```

In addition, a correction angle must be deducted (`- correction_angle`). The correction angle depends on the *Sprite*. If the *Sprite*

is looking to the right, the correction angle is 0: `correction_angle = 0`
is looking up, the correction angle is 90: `correction_angle = 90`
is looking to the left, the correction angle is 180: `correction_angle = 180`
is looking down, the correction angle is 270: `correction_angle = 270`

Rotate the player with `pygame.transform.rotate()` by the angle around its center:
(See also How do I rotate an image around its center using Pygame?)

```
rot_image = pygame.transform.rotate(Player_1, angle)
rot_image_rect = rot_image.get_rect(center=player_rect.center)

```

---

Minimal example: `repl.it/@Rabbid76/PyGame-RotateWithMouse`

```
import math
import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
player = pygame.image.load("player.png").convert_alpha()

#   0 - image is looking to the right
#  90 - image is looking up
# 180 - image is looking to the left
# 270 - image is looking down
correction_angle = 90

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

    player_pos  = window.get_rect().center
    player_rect = player.get_rect(center = player_pos)

    mx, my = pygame.mouse.get_pos()
    dx, dy = mx - player_rect.centerx, my - player_rect.centery
    angle = math.degrees(math.atan2(-dy, dx)) - correction_angle

    rot_image      = pygame.transform.rotate(player, angle)
    rot_image_rect = rot_image.get_rect(center = player_rect.center)

    window.fill((255, 255, 255))
    window.blit(rot_image, rot_image_rect.topleft)
    pygame.display.flip()

pygame.quit()
exit()

```

---
Tags: 2d, python, pygame, mouse, shooter
---


# Question
Title: Should abilities have their state and functionality separated?
I'm developing a top-down game using Javascript and Canvas in an ECS architecture.

I'm wondering, which of these is better from a design / elegance point of view?

**Method 1:** Combining the ability function and its metadata into one object:

```
// in ability factory
createBlinkAbility() {
  return {
    cooldown: 5000,
    castTime: 1000,
    hotkey: "q",
    execute(entity: Entity, scene: Scene) {
      let position = entity.get(CT.Position);

      let level = scene.queryComponent(CT.Level);

      position.x = Helpers.randomInt(0, level.width);
      position.y = Helpers.randomInt(0, level.height);
    }
  }
}

function executeCurrentCast(entity: Entity, ability: Ability) {
  ability.execute(entity); // all abilities have an execute function
}

```

**Method 2:** Separating ability metadata from its function:

```
// in ability factory
createBlinkAbility() {
  return {
    type: "blink",
    cooldown: 5000,
    castTime: 1000,
    hotkey: "q"
  }
}

// in ability factory
castBlink = (entity: Entity, scene: Scene) => {
  let position = entity.get(CT.Position);

  let level = scene.queryComponent(CT.Level);

  position.x = Helpers.randomInt(0, level.width);
  position.y = Helpers.randomInt(0, level.height);
}

function executeCurrentCast(entity: Entity, ability: Ability) {
  switch (ability.type) {
    case "bow": this.abilityFactory.castBow(entity); break;
    case "blink": this.abilityFactory.castBlink(entity); break;
    ...
  }
}

```

I know in general in an ECS architecture it is wise to separate "state" from "actions", but I'm not sure if this would also apply to things like abilities. It seems like it might be wise to maintain that separation, but the code seems like it might be "cleaner", or shorter at least, in the former case.

Lastly, I'm not really concerned with the performance differences between these two approaches, but rather which is better from a design standpoint.

# Answer
I'd argue you should keep the implementation alongside the definition in this case.

It gives you a *lot* of flexibility.

But .. You don't want to be serialising methods, so your players/NPCs should have references to the above via an ID/Key when serialised.

\[assuming the hotkey is not user-configurable, it's fine there. If it is, that should live elsewhere as part of a mapping for `hotkey` -\> `ability ID`\]

I'd suggest you want ability-specific properties stored alongside the method too (eg `NumberOfSecondaryTargets` or `BaseHealingRate`).

If you make sure your `execute()` method definition is as broad as possible to accommodate all ability use-cases, you can remain implementation-agnostic but flexible.

As an example, you could add an optional dictionary of parameter overrides to the execute method.

Say `{"DetectionRadius": 500}` which would allow special NPCs/scripted events to have more complete control over what happens with each invocation whilst remaining clean and easy to debug (it's up to you whether a mis-match dictionary key is ignored or throws a warning, etc).
> 1 votes

---
Tags: javascript, architecture, entity-system, design-patterns, component-based
---


# Question
Title: How to apply forces to character with gamepad in Unity?
I've been following Brackey's tutorial on this, see the excerpt from my code below. In his tutorial it only teaches "transform.Translate", how do I use this gamepad input system tool to add forces to the character to make them move instead? So I can have jump physics, and when they're in space they'll keep the momentum.

```
{
    NewControls controls;

    Vector2 move;
    Vector2 rotate;
    private void Awake()
    {
        controls = new NewControls();

        controls.Gameplay.Jump.performed += ctx => Jump();

        controls.Gameplay.Walk.performed += ctx => move = ctx.ReadValue<Vector2>();
        controls.Gameplay.Walk.canceled += ctx => move = Vector2.zero;

        controls.Gameplay.Rotate.performed += ctx => rotate = ctx.ReadValue<Vector2>();
        controls.Gameplay.Rotate.canceled += ctx => rotate = Vector2.zero;
    }

    private void Update()
    {
        Vector2 m = new Vector2(move.y, move.x) * Time.deltaTime;
        transform.Translate(m, Space.Self);**

        Vector2 r = new Vector2(rotate.y, rotate.x) * 100f * Time.deltaTime;
        transform.Rotate(r, Space.Self);
    }
}

```

To move with rigidbody controls, you have to use things like “forward” or “left” but I want one joystick to control the forward, backwards, and side to side movements. I don’t know how to use the joystick input for moving in all those directions. The tutorials have them as separate arrow keys

does anyone have some sample code, or a tutorial to point me to, or just some explanation? it would be much appreciated.

# Answer
I'm pretty sure I've solved my problem! I used

rb.velocity = new Vector3(move.x, move.y);

instead of

rb.AddForce(move.x, move.y);
> 0 votes

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


# Question
Title: What actions should I perform in DirectX 11 to correctly process Alt+Tab?
What actions, should I perform in a DirectX 11 application to correctly process `Alt+Tab` events from Windows?

My application is in fullscreen mode.

I expect my application to minimize to taskbar nicely, but it freezes for 20 seconds instead and no window minimization happens.

I know I can minimize the window by calling to `ShowWindow`, but what's up with the freeze?

# Answer
ALT+TAB is generally handled through `WM_ACTIVATEAPP` and "FSE" games switch out/in of fullscreen mode based on this message.

With DXGI you can manually implement ALT+ENTER using `DXGI_MWA_NO_ALT_ENTER` on the `MakeWindowAssociation` method. You then in your WndProc you detect it yourself processing the `WM_SYSKEYDOWN` message:

```
case WM_SYSKEYDOWN:
    if (wParam == VK_RETURN && (lParam & 0x60000000) == 0x20000000)
    {
        // Implements the classic ALT+ENTER fullscreen toggle
    }
    break;

```

That said, many games use 'fake fullscreen' instead of 'exclusive full screen' for better behavior when interacting with multiple monitors, ALT+TAB switching, etc. Exclusive fullscreen can get pretty quirky/tricky to do.

You can also just use 'fullscreen is really maximize without a window border' which is what I do for the directx-vs-templates to keep them simple. In other words, I never try to change the display resolution.

See DirectX Graphics Infrastructure (DXGI): Best Practices
> 3 votes

# Answer
Here is what I've found works. All of this information is probably scattered around the DXGI documentation on various disconnected pages; it's been a while since I've reviewed it.

For windowed modes (including borderless) Alt-Tab just works and you don't need to do anything special.

For fullscreen exclusive modes, first of all, **always** create your window (using CreateWindow(Ex)) with the normal title bar and borders **as if** it were for a windowed mode. **Never** touch them afterwards; SetFullscreenState will remove the window decorations for exclusive fullscreen modes automatically for you, so just let it do it's work and everything else will go easier on you.

---

An aside on MakeWindowAssociation

If you're using MakeWindowAssociation, you may have found that it doesn't honour the flags you give it, and DXGI tries to handle Alt-Enter (yes, I know you asked about Alt-Tab, bear with me) anyway. The correct way to use MakeWindowAssociation is to call it from the parent DXGIFactory for your swapchain, like so:

```
if (SUCCEEDED (SwapChain->GetParent (&IID_IDXGIFactory, (void **) &pFactory)))
{
    pFactory->MakeWindowAssociation (hWnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);
    pFactory->Release ();
}

```

My recollection is that none of this was clearly called-out in the documentation.

---

Deal with Alt-Tab by responding to WM\_ACTIVATE messages.

For Alt-Tabbing away, the **first** thing I do is call IDXGISwapChain::SetFullscreenState with FALSE. This **will** give you better behaviour, and you won't end up with any "frozen" topmost exclusive fullscreen modes.

The **next** thing I do is use ShowWindow with SW\_MINIMIZE - this nicely tucks the window away, minimized to the taskbar.

The **final** consideration is that this **will** generate a WM\_SIZE message with size {0,0} so when you're responding to WM\_SIZE for mode changing you need to be aware of this, and do whatever is needed for your program to stop it exploding in your face.

For Alt-Tabbing back, I do the following:

* SetForegroundWindow
* ShowWindow with SW\_RESTORE
* Pump my message loop to let everything bring itself up to date
* IDXGISwapChain::SetFullscreenState with TRUE.

All together, this gives a clean, smooth experience with no freezes, hangs, stuck foreground windows that you can't get rid of, or any other nastiness like that.
> 3 votes

---
Tags: directx11
---


# Question
Title: how to do rigidbody movement relative to player rotation in unity c#?
in my game the player is to walk around a sphere, I'm using rigidbody to apply movement with a joystick like this;

`rb.velocity = new Vector3(move.x, move.y)* speed;`

The problem is that when a character walks around a sphere, they rotate, so the movement gets messed up, how do I make them move relative to the current rotation and not the world?

I'm new to unity and coding in general so showing example code would help a lot!

# Answer
> 0 votes
This can be a one-liner:

`rb.veloxity = transform.rotation * move * speed;`

Multiplying a `Quaternion` rotation by a vector rotates the vector by that rotation.

Unity will also automatically promote a `Vector2` to a `Vector3` (or back), so we don't need to make a `new Vector3()` explicitly here.

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


# Question
Title: OpenGL - Debug version runs faster than Release version
My Visual Studio 2019, 64-bit version of Tetris using OpenGL runs significantly faster, 3X, in Debug mode than in Release mode.

The image above shows the board. Each cycle of the rendering or game loop redraws everything, viz., the light blue background, the grid, the individual game pieces (one shown) with the latest one added moving every 300 ms, and the text score display. I have moved all the repetitive code out of the loop, e.g., that which sets the location in shaders for uniform constants.

The Release mode loop cycle time ranges from 0.05 to 1390.0 ms while that of the Debug mode ranges from 0.05 to 350.0 ms.

Any thoughts on what I might investigate?

Thanks.

# Answer
> 0 votes
I ran timing analysis on 4 sections of the rendering (game) loop to see if I could find a recurring problem. The 4 sections were drawing the background and grid, the game piece(s), and the score. All of them were mostly low time, on the order of 0.001 to 0.01 milliseconds, except for an occasional 35 to 400 millisecond spike.

The Windows 10, x64 computer I used has 2 video graphic cards. They are Intel UHD Graphics 620 and NVIDIA 2GB GeForce MX130. The former is used for **everything** on the system by default while the latter has to be specifically assigned for any given executable.

I assigned the Tetris release executable to the NVIDIA card and the problem disappeared. The times for the 4 drawing sections were also far more consistent, i.e., had a lower standard deviation.

I suspect that the Windows system was demanding the periodic use of the Intel graphics system relegating my application to a lower status during that demand.

This does raise the interesting question of what happens when my Tetris is deployed to a system with a single graphics card. I do not know if the game can be made a priority so it does not do herky-jerky movements.

---
Tags: opengl, c++, visual-studio
---


title: Mathf.PingPong equivalent in Java

text:
# Question
Title: Mathf.PingPong equivalent in Java
I am making a 3D game with java using the Processing 3 framework. I need the `Mathf.PingPong()` function from Unity so that I can make a bouncing ball. Unfortunately, there is no `Mathf.PingPong()` in Java. Any alternative methods to do this?

# Answer
Unity has open sourced their C# runtime to be used as a reference, so you can go checkout how the function is implemented and reimplement it in Java: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Mathf.cs#L362

In case the link dies, here is the gist of the implementation you'd need to translate to Java:

```
public static float Repeat(float t, float length)
{
    return Clamp(t - Mathf.Floor(t / length) * length, 0.0f, length);
}

public static float PingPong(float t, float length)
{
    t = Repeat(t, length * 2F);
    return length - Mathf.Abs(t - length);
}

```
> 3 votes

---
Tags: unity, java, processing
---


# Question
Title: Offscreen waypoint indicator using X and Y screen position
I was wondering how I could achieve an offscreen indicator effect that helps direct the player to the next waypoint. My game is 3D, most solutions I have found are for 2D games (i.e Asteroids).

See this example of Warzone. I have highlighted the parts that I am interested in creating.

The engine I am using has an API call to convert from world to screen position. This only returns the X and Y components though. Do I need the Z component to achieve what I am after?

From what I understand so far:

* Check if target is off screen
* If off screen convert 3D world position to 2D screen position (only X and Y components)

The Math for snapping the 2D UI icon to the side of the screen so it moves around is where I get lost. I read something about slope intercept is something that can solve this but am not sure how to apply it to my problem.

If it helps I will be writing this in JavaScript, however, I'm not after a language specific solution, am really interested in understanding the Math so I can write it myself for any language.

# Answer
> 2 votes
I assume that this API method you're talking about projects the point onto camera's near plane. That would mean that you get point on screen so that `X=-1` is left border, `X=1` is right border, `Y=-1` is bottom and `Y=1` is top. If that is the case, then you have to clip this X, Y point to your camera boundaries, which should be in normalized coordinates as \[-1, 1\], something like `icon.X = max(-1, min(X, 1))`. That should do the trick. You do that in both dimensions X and Y.

Additional check for world point being "behind" player could be good to manually snap the icon to the bottom of the screen: if waypoint projected onto player's forward vector points back AKA `dot(forward, wapointPos-playerPos) < 0`, then `icon.Y := 0`.

Another way (assuming you already have a code that checks if world point is in camera's cone of vision) is comparing the sign of dot product between the waypoint vector and camera's right. If `dot(right, waypoint) > 0` then icon is on the right border, otherwise on the left. This generalizes to 3 dimensions by repeating this check for Y. You just have to think in planes `camera.forward, camera.right` for positioning on left/right border and in `camera.forward, camera.up` for positioning on the top/bottom border.

If you lack the code to check if point is inside camera's cone of vision, then you would have to do something like this:

1. project the waypoint onto camera's `near` plane
2. clip the point to camera's boundaries.

You can use intercept theorem to project the point onto camera's near plane (check out the picture). Additional work is required to translate the projected vector to normalized coordinates of near plane (for example calculate using FOV and projecting on camera's right vector)

```
// waypoint vector
let W = (waypointPos - playerPos);
// x like in picture
let x = (near * W.length() / dot(W, forward))
// waypoint projected onto near plane (forward is camera's forward vector)
let W' = W * x / W.length() ; // watch out for overflow
// check if camera waypoint is behind neaer plane of camera
let glueBottom = dot(forward, W') < near;
// translate W' to screen coordinates [-1, 1]
// ...

```

Key aspect is projecting vectors onto right planes - but planes are always determined by two other vectors, so you just use them to project correctly.

---
Tags: mathematics
---


# Question
Title: Borderless windowed (fake fullscreen) mode doesn't cover the entire screen
I'm using Direct3D 11 running on Windows 10 20H2, but have seen this problem going back to Windows 7.

I'm adding borderless windowed (fake fullscreen) mode support, and all of the online resources I can find suggest that it's simple: just setup a windowed mode the same size as your display resolution, use WS\_POPUP, and that's all you need to do.

**The problem is that it doesn't actually work**.

Instead, I get (on a 1920x1080 display) a 1920x1060 window, with the bottom 20-pixel high portion of the taskbar still visible. The odd thing is, the swapchain backbuffer *is* sized correctly, at 1920x1080, and adding some debug output shows that my WM\_SIZE message *is* coming through at 1920x1080; it's as if something else internal was preventing the window from covering the full screen.

Fullscreen exclusive modes work correctly.

The workflow I'm using to set this mode goes like:

* Determine if the window will be the same size as the display.
    + If so, set WS\_POPUP (not sure what to use as the ExStyle so I'm leaving it at 0 for now, but I've also tested WS\_EX\_TOPMOST with no success).
    + If not, set the usual array of styes.
* Call SetWindowPos with SWP\_FRAMECHANGED.
* Pump my message loop to make sure that everything is brought up to date.
* Call IDXGISwapChain::ResizeTarget to do the actual window resizing.
* Respond to WM\_SIZE to call IDXGISwapChain::ResizeBuffers, create my views, etc.

Of note is that I *don't* change the window size using SetWindowPos; I let IDXGISwapChain::ResizeTarget do that for me, and that works for every other combination of windowed-to-windowed, windowed-to-fullscreen, fullscreen-to-windowed and fullscreen-to-fullscreen transition (where "fullscreen" here is fullscreen exclusive).

The only thing that does *not* work is borderless windowed.

What sorcery am I missing?

# Answer
> 3 votes
> *It can only be attributable to human error. This sort of thing has cropped up before, and it has always been due to human error*.

**This was, of course, all my own fault**.

I had some code for centering the window after a windowed mode transition, that called `SystemParametersInfo (SPI_GETWORKAREA, ...` and centered the window taking account of the taskbar positioning/etc.

**This was what was causing my problem**.

The major clue I had was that on closer examination, a small portion of the top of my window seemed to have also been sliced off, which led me to question if it was just a problem of window positioning.

Everything works correctly now, and as a bonus I got to fix a nasty little bug I've had in code I've been using for years.

Maybe this question and it's answer will be useful to someone else who has a similar problem in the future?

---
Tags: directx11, fullscreen
---


# Question
Title: How do I make my turn based battle system scalable?
I’m currently working on a turn based battle system for my game. The game is in unity coded with c#.

The turns are based off of an initiative system determined by each characters speed. Right now I have a turn manager that got a queue of all the characters. Then to increment the turns I enqueue the current active character, then dequeue and set them as active.

All of the tutorials I see online use an `enum` to make a basic battle state system. I am thinking about implementing this next but I am wondering if this is the best approach or if there is different systems that are more scalable.

# Answer
> 1 votes
I don't know if this is "best", but the system I set up for turn-based RPGs I'm working on is certainly *one* flexible way to architect turn-based combat. It leans heavily on some Unity-specific features, but then you are tagging this question Unity.

I have the entire main gameplay loop encapsulated in a method called AdvanceTurn(). That method first gets the active unit's action (it tells the GUI to ask for the player's choice, or it runs AI for enemies), executes that action, and finally checks if anyone has died/the combat ended.

This method is a coroutine, and I use WaitUntil() between each step in the coroutine to pause it until ready to proceed to the next step. For example, after requesting the player's choice, it'll WaitUntil(gui.PlayerMadeChoice). Or when executing actions, it'll WaitUntil(scene.AnimationsComplete).

AdvanceTurn() is itself being run in a loop within a coroutine, looping until the combat is over, something like this:

```
while (!combatEnded) {
    if (combatants.Count == 0) {
        SetupInitiative(players, enemies, combatants);
    }
    yield return StartCoroutine(AdvanceTurn(combatants.Dequeue()));
}

```

---
Tags: unity, c#, rpg, turn-based
---


# Question
Title: Why does my PBR material appear grey in game?
I am playing around with PBR materials and I cant get them to work correctly. When I create a material using PBR the model appears gray in game. Any ideas on why I’m not getting the same result?

```
val floorMaterial = Material(assetManager, "Common/MatDefs/Light/PBRLighting.j3md")
floorMaterial.setTexture("BaseColorMap", assetManager.loadTexture("Textures/Floor_Diffuse.png"))
floorMaterial.setTexture("NormalMap", assetManager.loadTexture("Textures/Floor_Normal.png"))
floorMaterial.setTexture("SpecularMap", assetManager.loadTexture("Textures/Floor_Specular.png"))
val sun = DirectionalLight()
sun.color = ColorRGBA.White.mult(1.3f)
sun.direction = Vector3f(-.5f, -.5f, -.5f).normalizeLocal()
main.rootNode.addLight(sun)
val lightProbe = LightProbe()
lightProbe.position = Vector3f(0f, 10f, 0f)
addLight(lightProbe)

```

For comparison when I use regular lighting this is the result

```
val floorMaterial = Material(assetManager, "Common/MatDefs/Light/Lighting.j3md")
floorMaterial.setTexture("DiffuseMap", assetManager.loadTexture("Textures/Floor_Diffuse.png"))
floorMaterial.setTexture("NormalMap", assetManager.loadTexture("Textures/Floor_Normal.png"))
val sun = DirectionalLight()
sun.color = ColorRGBA.White.mult(1.3f)
sun.direction = Vector3f(-.5f, -.5f, -.5f).normalizeLocal()
main.rootNode.addLight(sun)
val lightProbe = LightProbe()
lightProbe.position = Vector3f(0f, 10f, 0f)
addLight(lightProbe)

```

# Answer
I eventually got it working with a prebuilt light cube. https://github.com/Simsilica/Spix/tree/MaterialEditor/proto/assets/Probes
> 0 votes

---
Tags: materials, jmonkeyengine, pbr, kotlin
---


# Question
Title: Right way to dispose of a WWW IEnumerator after it has completed - Unity
What is the "right" way to dispose of an Ienumerator coroutine after it has completed?

# Answer
Do nothing.

You let the IEnumerator method run to the end and then let the garbage collector take care of it automatically.

C# is a garbage-collected language. There are very few edge cases where you need to dispose things manually, and this isn't one of them.
> 1 votes

---
Tags: unity, web, memory
---


# Question
Title: Behaviour Trees: How to clean up when a sequence is interrupted?
I'll try to show my problem on a minimal example, in reality it's more complex:

It's a simple behaviour, that repeats "an action" that has a certain animation. If a player gets close, this sequence gets interrupted and the AI executes the "Flee" action.

The interruption happens because the top level selector is "dynamic" which in Unity/NodeCanvas means, that its higher priority nodes get executed every frame and if they succeed they interrupt the lower priority ones.

My problem is shown via the red arrow - if the "action" gets interrupted, the clean up (in this case "stop animation") doesn't execute.

What is the best practice to handle the clean up? Is my setup flawed? Or should I just be using a different interrupting mechanism?

Thanks for any help!

# Answer
> 1 votes
Make the cleanup part of the "Flee" node. When it wants to make the actor flee, then it first needs to make sure that all the pre-conditions which are required for fleeing are fulfilled. Like stopping any ongoing animations.

---
Tags: unity, ai, behavior-tree
---


# Question
Title: SAT - penetration and pull out vector based on previous body position
I implemented SAT alghorithm that is able to detect collisions and return shortest "pull out" vector. On the screenshot below this vector is determined by yellow color (P and Q). If I add Q vector to position of body B, then will be no collision.

However I realized that I can't use this vector to solve collisions, because the body could arrive from completely different direction. I should rather pull out body B by using direction of vector Z.

I already tried to calculate additional overlap by using axis determined by vector Z. However in such case I'm pulling body B too far away from A.

Is there any ellegant solution for that by keep using SAT algorithm?

# Answer
> 2 votes
I think I found an answer for my question by using SAT algorithm only. Of course I'm completely ignoring tunneling effects.

Let's say we have shapes A and B. Shape B penetrated shape A. We know old position of shape B (before the collision). We already did some collision test (SAT) and we know that the collision between shapes A and B exists. Let's draw an axis P determined by old and new position of shape B.

Now project all vertices of shapes A and B on axis P.

Now we can move shape B by using vector Z calculated by formula: Z = UNIT(P) * (Amax - Bmin)

Where UNIT(P) is unit vector of axis P.

The collision has been removed, because now we have at least one separating axis. However, we are not ready yet. Shape B is too far away from A. We need to snap shape B to A on axis P.

Let's repeat SAT test, but this time we are looking for gaps.

We found a gap on axis Q. The length of the gap can be calculated easily. We also know the angle between P and Q and we can calculate snap vector S.

Now we can add vectors Z (initial pull out) and S (snap).

# Answer
> 1 votes
Likely not as elegant as you're hoping for, unfortunately.

SAT is primarily for collision detection between two convex shapes, not collision response. So you're already down a bit of a rabbit-hole. You could implement a sweep test (rectangle-rectangle-sweeptest in this case) to help you identify the optimal response to the collision. i.e. point, direction, and duration of the collision.

Something like what's shown here - http://supertux.lethargik.org/wiki/Sweep\_collision\_algorithms

I wish I had a better answer for you, kudos for using SAT though! :)

---
Tags: separating-axis-theorem
---


# Question
Title: How do I make sure my tic-tac-toe AI always plays to a draw?
I'm working on a little project. The aim is to play Tic-Tac-Toe against an AI, but I require that the game always results in a draw against the AI opponent. How can I implement the AI to ensure that?

# Answer
It is possible. Probably the best way to program an AI for tic-tac-toe that could do this is to use a minmax algorithm.

Normally, you would give a winning move a very high score so that the AI would make that move. In your case however, you would want to give a winning move a very low score and instead favor moves that prevent the opponent from winning. This means that moves that either let the player win or the AI win would be very low scoring moves and every other move would be high scoring.

Now, this still doesn't guarantee a draw 100% of the time. If the player puts the AI into a position where no matter what move it makes it will win, the AI will of course win. However, this should help the AI force a draw the majority of the time.
> 1 votes

# Answer
Don't be confused by calling this game tic-tac-toe, it is its own game, and might or might not be as easily solvable as tic-tac-toe. Your game is "player1 wins by a tic-tac-toe draw, player 2 wins by either a tic-tac-toe win or loss." (Or the converse).

If you think about it, either this game is a win for the first player, or it's a win for the second player, so if you have to play both sides, your task is impossible. Your instructor is playing a little trick on you.
> 1 votes

# Answer
I have done a project similar to this about a year ago. I researched strategies on how to always win/tie the game, and simply coded the strategies - though it does take some time - into my game (NOTE: make sure to plan out an efficient way for the computer to analyse the "board" and then make its next move, or else you will end up with a giant mess of if statements). I would recommend reading this article on wiki how. It clearly explains what to do to win/tie a game regardless of what your opponent does.

This project is possible and solvable! Good luck with it!
> 0 votes

# Answer
Well... There's only 9! or 362880 possible games. Less, since you stop playing after someone wins. And less, conceptually, once you reach a state where neither player can win. Times 2 if you want to treat X and O starting as different cases.

At any moment, the number of possible board states is 3^9 or 729. Each of nine cells has one of three marks in it (blank, X, O). Less, since many combinations can't happen in a game.

At any rate, these are very small and tractable numbers. One could, in a pleasant afternoon's coding, perhaps in node.js or python, iterate over all those games, and produce a table showing for each of the 729 board states, which move to make next.

Print it out as one long line of javascript. It could be to initialize an array, or print out a giant switch statement or mess of if-statements. Doesn't matter, computers don't mind. Paste that into your function nextMove(){}, and, done!
> 0 votes

# Answer
What you have to do to get a draw is easy. But you're going to have to go on impossible mode.

First, you're gonna put X/O in the bottom right corner. The AI should put the X/O in the middle. Then you are going to put an X/O beside it going sideways. AI should put one to stop you at the end of the bottom line. You are then going to put an X/O in the top right corner. Then one at the Middle row left side (the one on the farthest left side). Then finally after the AI goes you should put the final X/O in its place for a draw.
> 0 votes

---
Tags: javascript, ai
---


# Question
Title: Crate destroy when in trigger and button E pressed
There are no errors in the console but I feel like im doing something wrong. The crate is not destroying when I click E.

```
public class CrateDestroy : MonoBehaviour
{
    public GameObject crate;

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                Destroy(crate);
            }
        }
    }
}

```

# Answer
Solved Make sure to have the trigger collider in same game object as the script.
> 1 votes

# Answer
Although your code already works and your problem is solved, the script can be cut down a little bit and become a bit more efficient. Instead of using an `if` statement wrapped in another `if` statement, you can simply combine the two together, as seen below:

```
void OnTriggerStay2D(Collider2D other)
{
    if (other.CompareTag("Player") && (Input.GetKeyDown(Keycode.E)))
    {
            Destroy(crate);
    }
}

```
> 0 votes

---
Tags: unity, 2d
---