# Question
Title: How can I Implement spin in billiard game?
I'm not sure that you played billiard or snooker before.if you played you should know about spin. but anyway if you don't know about it you can see it in this video

I want to Implement spin like this game

for example difference between Top spin and Back spin is:

**Top spin**

**Back spin**

---

**Spin behaviour**

if you aim behind the ball you can shoot the ball in all direction

---

if you aim closest to right you can just aim the right

if you aim closest to left you can just aim the left

---

I found a same Issue that used Torque in stackoverflow but I don't know why didn't work!

**Top Spin**

```
GetComponent<Rigidbody>().AddTorque(Vector3.back * cueStrength );
GetComponent<Rigidbody>().AddForceAtPosition(cueStick.forward * cueStrength,transform.position,ForceMode.Acceleration);

```

**Back Spin**

```
GetComponent<Rigidbody>().AddTorque(Vector3.forward * cueStrength );
GetComponent<Rigidbody>().AddForceAtPosition(cueStick.forward * cueStrength,transform.position,ForceMode.Acceleration);

```

I noticed that flyordie's snooker didn't use AddTorque.so I don't need answer that Implemented with AddTorque.

---

# Update

**What I tried**

I add joystick to select spin angle

then I apply spin force ( It seems my spin works but sometimes didn't work that I attached video in end of my question).

this is my code:

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

public class MainBall : MonoBehaviour {

    private Vector3 FirstPos; // store first position as reset position
    public Transform SpinRoator; // spin rotator cylinder that show spin angle
    private Rigidbody rigidbody;
    public bool SpinUsed; // spin should use once
    private float v2;

    private void Start() {
        rigidbody = GetComponent<Rigidbody>();
        FirstPos = transform.position;
    }

    //After goal reset ball position
    public void ResetPos(){
        rigidbody.velocity = Vector3.zero;
        rigidbody.angularVelocity = Vector3.zero;
        transform.position = FirstPos;

    }

    void SpinForce(){
        SpinUsed = true;
        float F = ComebackForce(); // calculate comeback force
        StopBall(); // stop ball
        rigidbody.AddForce(SpinRoator.forward*F);// apply spin force
    }

    // calculating return force after hitting f = m.a
    float ComebackForce(){
        var m = rigidbody.mass;
    var v1 = rigidbody.velocity.magnitude;

    var a = (v1 - v2) / Time.deltaTime;
        var F = m * a;
        v2 = rigidbody.velocity.magnitude;
        return F;
    }

    //stop ball
    public void StopBall(){
      rigidbody.velocity = Vector3.zero;
        rigidbody.angularVelocity = Vector3.zero;
    }

private void OnCollisionEnter(Collision other) {
    if(other.collider.tag == "Ball" || other.collider.tag == "ColorfulBall"){
    if(!SpinUsed){
    SpinForce();
    }
    }
}
}

```

# but What is Problem?!

It seems works correctly but My Problem is sometimes Spin don't work correctly you can see this video that demonstrate this problem.my ball goes wrong direction of spin!!!

**1.Ball goes Wrong sometimes**

as you can see in above gif ball goes wrong direction!!! ball should go along yellow cylinder but I don't know what is problem of my code!!!

**1.Ball goes slow sometimes**

another problem is comeback force is slow sometimes!!! I calculate comeback force `F = m.a` but why is it slow?!

# Answer
I don't know if my idea will be good enough for you, but you can try it - maybe while aiming, you can store the info on what did the player do (a simple way would be to store a vector... "Player aimed at center horizontally and +5% vertically) and then, when you hit a ball, stop it completely for a frame and add a force that would be calculated with the spin included?
> -1 votes

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


# Question
Title: My SVG graphics don't look as good in Unity as they do in my web brower
I thought had an easy solution to getting nice smooth edges on all of my images: export them to .svg and then use Unity's new SVG importer package. However, my svg images don't really look better once they get into Unity. They don't look worse than my .png images but they don't look as nice as they do when I'm looking at them in a web browser or photo viewer.

Why is that? And is there a simple way to fix that?

I did try out as a 'Textured Sprite' instead of a 'Vector Sprite' and noticed some quality differences messing around with Sample size and Filter mode but I wasn't able to get the .svg images to look as good as they do in a regular image viewer.

ETA images:

SVG image in a viewer or web browser (This is ideal):  SVG image in Unity when object is close. It's okay but not as good. A little fuzzy plus it adds some random notches:  SVG image in Unity when object is far. More fuzzy:

PNG image in Unity when object is close. Very good:

But PNG image in Unity when object is far. Very fuzzy:

# Answer
This is not a true answer but I'm posting this in case is helps someone.

I have decided to stick with .png for now. As yet I don't see enough of an image-quality improvement with .svg. (If someone has figured it out though please post!)

2 things that have helped me though:

* In doing my own basic graphics, setting the initial graphic setting to 600 dpi rather than 300 dpi helped moderately in certain cases.
* If you have control over the look of the images, it appears that having an outline as part of the image seems to call extra attention to the jagged edges that appear, so consider avoiding them.

Wish I had a better answer. If I find one, I will update.
> 1 votes

# Answer
Your PNG problem could be mitigated by enabling mip-maps and using trilinear filtering.
> 1 votes

# Answer
**Unity 2018+**

You need to import the Vector Graphics package.

https://stackoverflow.com/questions/52562020/how-to-import-svg-to-unity-2018-2

> In order to import SVG with Unity 2018.2, you need to import the package Vector Graphics with the new Package Manager (you can find it in the menu Window \> Package Manager).
>
> Then, you can import any SVG in the project by copying it in the project's folder.
>
> Beware of the options in the inspector, the Generated Asset Type controls the render mode, there are 3 modes: Vector sprite (default), Textured sprite, Texture2D.

---

**Unity 2017-**

Unity does not natively support vector graphics, so you will need to use another format.
> 0 votes

---
Tags: unity, image, svg
---


# Question
Title: Developing addons for xbox one controller
I want to develop an addon that plugs to the bottom of the controller for the xbox one. Can I legally make addons to the xbox one controllers without Microsoft's blessing?

If so, has anyone done anything like this? Cursory search looks like it has not been done.

# Answer
If you want to interface with the controller electronics — ie. to communicate with the controller or console — then you will definitely need Microsoft's blessing.

The expansion port pinout, protocol, and API for communication with the controller/console are not publicly available, so you would need to be a registered Xbox One developer to start with. There may be additional licensing or technological restrictions that require Microsoft's assent or participation to produce your own accessories that will work with the device.

(I don't want to stray into details that might be guarded by NDAs. Suffice it to say I worked on a project where we developed a custom controller attachment that we could not have accomplished without Microsoft's approval)

---

If you just want to clip your add-on onto the controller, without drawing power from it or communicating electronically, then that's less clear to me. I don't know to what extent the physical shape of the controller or its interconnection points might be protected by patent, trade dress, or other intellectual property laws in the relevant jurisdictions.

It's conceivable that if you made a non-communicating attachment that Microsoft objected to, they could send you a cease and desist notice or pursue legal action against you. Whether you could successfully defend against such an action is a question you should take to a lawyer for a more informed opinion.
> 1 votes

---
Tags: controllers, xbox
---


# Question
Title: Godot: How do I asign movement cost to tiles in a Tilemap?
**Pathfinding**

I am trying to apply godot's Navigation to create a pahtfinding enemy in a Platformer game. I've read about a method to allow for pathfinding to take into account gravity.

My issue is that what I know I must do is to add more movement cost to higher tiles.

How do I do this?

**EDIT**

I have since found the documentation for the Astar Node. Wish me luck.

# Answer
**The Astar Node**

Godot has an Astar node for pathfinding.
> 1 votes

---
Tags: path-finding, platformer, godot
---


title: Godot: 'is_on_floor' problem

text:
# Question
Title: Godot: 'is_on_floor' problem
I have a character in a basic platformer game and am having trouble.

Whenever my character stands over two tiles on a tilemap and appears to be directly colliding with them the character's *is\_on\_floor* variable toggles constantly between true and false, messing with my jump physics. Standing on a non-tilemap object.

My collisions have been checked and are fitted to each object. my tiles are at a 24 * 25 in size.

**edit**

I have recently been working with sloping tiles and have encountered a similar problem after having changed my collision box into a capsule.

How do I fix this and what is causing this?

# Answer
**Switch to 3.1**

The problem seems to be fixed in 3.1
> 0 votes

---
Tags: collision-detection, loading, godot
---


# Question
Title: Rotate perspective camera to align screen width to procedural object's width (Unity, C#)
I give up. After much trying and searching, I have to say I was unable to achieve the following task, for which I must call for your wise advice.

In my current Unity 5 application (using C#), there is a procedurally generated object (therefore with variable shape) to which the camera should be aligned when players hit a given key. By aligned, please understand it making the width of the screen parallel to the longest part of the object. The idea is represented in the following picture, where in black one can see the irregular object, in yellow is the bounding box.

In other words, it means that I want the camera to be rotated so to align to the longest side of the object's bounding box. I tried that. Still, I was unable to properly calculate the correct angles so to rotate the camera in a way that the horizontal axis of the screen becomes parallel to the width of the objects' bounding box.

Any help would be much appreciated.

# Answer
Calculate the angle of the bounding box (or the angle between the 2 furthest points). `Vector3.Angle(bounds.max - new Vector3(bounds.max.x, bounds.min.y, bounds.max.z), Vector3.right)` Then simply set the camera's rotation to that angle. Repeat as necessary for each dimension.
> 1 votes

# Answer
Not sure if this would work for your game as you might’ve missed some details but if the position is always the same, why don’t you just hit the object with rays from all sides and determine with those values it’s dimensions.

You could position several “ray sources” from each horizontal, vertical and diagonal side and work with those values, so shortest distance is the longest side.

I can see how determining the shape would be difficult like that but if you run a few tests and develop an algorithm in a function that would do it for you.

Since it’s irregular this might be inaccurate though but it depends on how irregular it can be, in any case the solution would be: more rays
> 0 votes

---
Tags: unity, camera, geometry, screen, procedural
---


# Question
Title: Finding a path with minimal number of turns on a grid?
There is a path, generated by my implementation of **A\***, where **diagonals aren't allowed**, and the **heuristics is the Manhattan distance**.

Is there a way to **always or nearly always find a path with the least amount of turns**? Even if it's a **bit longer**, and even if it **costs more computationall**y.

Or is there a way to **algorithmically "fix" a path** later? Like on the image below, **cut those long detours** and **replace them** with those **blue parts**.

My current version is far from optimal, both length-wise, and both turn-wise. I also tried **multiplying the heuristic value** of a tile, if:

* it isn't going in the same direction as the line made from the previous 2 tiles. But that didn't help either.

# Answer
First fix your A\* implementation so that it will find the shortest path.

Adjust the *cost* of the turn instead of the heuristic. This means that when you generate the neighbours the one going straight ahead gets cost 1 and the one where you make a left or right gets a higher cost depending on how large a detour you accept.

This means that every tile can get *up to 4 nodes* in the A\* graph, one for each direction the entity can come from. For the purpose of A\* you have to treat them as separate nodes.

It is fine if the heuristic *underestimates* the total cost, but not if it overestimates. So manhattan will still be good enough.
> 4 votes

---
Tags: path-finding, tilemap, grid
---


title: WaitForSeconds error

text:
# Question
Title: WaitForSeconds error
I'm new to c# and coding, sorry if I sound like a noob... I don't know how to fix the waitforseconds error, and I don't know what's wrong.

```
public float restartDelay = 2f;

public TextMesh failText;
public TextMesh failTextGame;

private void Start()
{
    failTextGame.text = "";
}

System.Collections.Generic.IEnumerable<bool> OnTriggerEnter(Collider other)

{
    if (other.gameObject.CompareTag("Wall"))

    {

        failText.text = "Game Over!";
        failTextGame.text = "Try Again";
        yield return new WaitForSeconds(restartDelay);
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

```

}

# Answer
Calling `WaitForSeconds` inside of the `OnTriggerEnter` function **is perfectly fine** since this function can be handled as a coroutine by Unity. Having an additional function is not needed.

The only problem with your code is the **return type of the function**

```
System.Collections.Generic.IEnumerator OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Wall"))
    {
        failText.text = "Game Over!";
        failTextGame.text = "Try Again";
        yield return new WaitForSeconds(restartDelay);
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

```
> 2 votes

# Answer
Sean’s answer is correct. However, since all you are doing is waiting before calling a method, you could just use `Invoke` instead:

```
private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Wall"))
    {

        failText.text = "Game Over!";
        failTextGame.text = "Try Again";
        Invoke("Restart", restartDelay);
        //Alternatively, if you are using a version of C# that supports nameof:
        //Invoke(nameof(Restart), restartDelay);
    }
}

private void Restart()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

```
> 1 votes

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


# Question
Title: Raycasting from an object to the center of the screen (crosshair) without clipping through objects
Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair.

Using `ViewportToWorldPoint` I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below.

The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be.

Am not sure how to solve this.

```
void Update(){
    Vector3 ray = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f));

    line.SetPosition(0, transform.position);

    RaycastHit hit;

    if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)){
        if(hit.collider != null){
            line.SetPosition(1, hit.point);
        }
    } else {
        Vector3 pos = line.GetPosition(0);
        line.SetPosition(1, ray + (Camera.main.transform.forward * raylength));
    }
}

```

The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool

# Answer
You need to fire two rays:

1. The first ray is fired from the player's-eye view, to find out what's under the crosshair, so you know what worldspace point to aim at. The closer that point is, the more you need to angle your shot inward to hit it.
2. The second ray is fired from the tool/weapon muzzle, toward the hit from the first ray. This will tell you what a shot or beam fired from the device will hit first on its way toward the target.

You might also want to use spherecasts for one or both of these checks, if your beam has much thickness or you have a lot of tight corners and gaps to shoot around. This ensures the 0-width ray doesn't miss something that it looks like we should have hit.

```
Vector3 GetHitPoint(Vector3 muzzlePosition) {
    // Unless you've mucked with the projection matrix, firing through
    // the center of the screen is the same as firing from the camera itself.
    Ray crosshair = new Ray(camera.position, camera.forward);

    // Cast a ray forward from the camera to see what's
    // under the crosshair from the player's point of view.
    Vector3 aimPoint;
    RaycastHit hit;
    if(Physics.Raycast(crosshair, out hit, rayLength)) {
        aimPoint = hit.point;
    } else {
        aimPoint = crosshair.origin + crosshair.direction * rayLength;
    }

    // Now we know what to aim at, form a second ray from the tool.
    Ray beam = new Ray(muzzlePosition, aimPoint - muzzlePosition);

    // If we don't hit anything, just go straight to the aim point.
    if(!Physics.Raycast(beam, out hit, rayLength))
        return aimPoint;

    // Otherwise, stop at whatever we hit on the way.
    return hit.point;
}

```
> 3 votes

---
Tags: unity, raycasting
---


# Question
Title: How can I sync billiard balls in network?
I'm developing a billiard game my problem is I don't know how can I sync balls in network

I use forge for networking but feel free to answer photon or unet because I know them.

# What I tried

1.sending position and rotation of each ball in network

2.sending force direction and Intensity inside network

```
networkObject.SendRpc(RPC_SHOOT,Receivers.AllBuffered,force);

    public override void Shoot(RpcArgs args)
    {
       Vector3 Force = args.GetNext<Vector3>();
       GetComponent<Rigidbody>().AddForce(Force);
    }

```

I don't know why but when I send force direction and Intensity in network sometimes Physics is different! I asked this question in forge forum and they tell me:

> It's non-deterministic It's how most physics simulations work Because of floating point inaccuracies and different CPU architectures and a whole load of other factors That's how PhysX works Well PhysX is technically deterministic for the same inputs But all inputs have to be identical

# source is available:

https://github.com/smkplus/BilliardNetwork

# Answer
In **UNET** I’d just add a **Network Transform** to all the balls and that would easily take care of position and rotation. I’m not sure about forge though.

If that’s not an option, why don’t you just use something like RPC to add force, the problem could be that physics might act a bit different for both clients though.

So another option could be to create a separate game object to store ball positions, and at the end of every turn they would get updated by the last player, and then checked on each client if the positions of the balls are the same as values, if not then move them.

Hopefully this helps you, that was just some ideas.
> 1 votes

# Answer
In a networked scenario, you should not try to rely on physics determinism to keep your simulation in sync.

Even if both players are running identical binaries on identical chips, the difference of a single fixed timestep due to network latency, or a single object being spawned in a different order due to any optimizations happening in the engine's internals, is enough to introduce divergence.

---

Since billiards is a turn-based game, the simplest and most robust approach is to alternate authority over the simulation.

The player who takes the shot simulates the physics locally, and sends position & orientation updates to all other clients, who are for the moment just spectators.

Each spectator maintains a buffer of recent updates from the current player, and uses that buffer to show a state some time in the past. Not far - just enough to be able to absorb the occasional missed or delayed packet without visibly stuttering. This lets them always show an interpolation between two actual positions & orientations that occurred in the current player's simulation - they never need to extrapolate or simulate the behaviour themselves, and the balls always end up exactly where the current player's sim settled.

You may need to adjust the interpolated position slightly, to ensure a ball doesn't sink into the table on its way into a pocket, or to ensure the ball doesn't take a shortcut when changing direction, blunting what should have been a sharp collision, but these are purely visual fix-ups that don't affect the final gameplay state of the table in time for the player's next turn.

Then you switch authority and the next player takes the shot.

Note that this only works if you're willing to trust each client to fairly report their play. If hacking is a concern for your game, then you'll want to use an authoritative server under your control, and let all players see a copy of the simulation from the recent past. You can a wind-up animation of the pool cue to cover the latency before the first results from the server are available.

---

A more robust, but also more intensive solution is to compute the trajectories yourself, so you're not at the whims of a fully general physics solver, and can control the operation explicitly. I wouldn't do this for most games, but for billiards the problem space is reasonably small and well-studied, so it would be feasible to write a "billiards engine" that solves just this case exactly the way you want it.

Since you're no longer bound to iteratively approximating the outcome frame by frame, you could have one client compute the full future of the table at the moment the ball is struck, and transmit the exact sequence of actions to the other clients like a set of animation keyframes.

You could even use fixed point math to sidestep the complexity of getting floats to agree between binaries / differing hardware. Then the player could simply send their action with the pool cue, and all spectators (or the central server) can independently reproduce the outcome of that action (and check each others' work to spot cheating).
> 1 votes

---
Tags: unity, c#, networking, billiards
---


# Question
Title: Attaching a swinging object to a rolling object?
I am new to Unity and attempting to create a platform that hangs down under a roller that runs on rails. I've gathered my objects and come so far but I can't for the life of me work out how to attach the platform to the roller on top without the rope connecting them getting wound up on the roller as it goes along.

Is there a way to make sure only the roller turns but the rope attached just follows it vertically and horizontally?

# Answer
> 1 votes
Just write a script that on fixed update matches the position but not rotation. I've never worked with unity's physics constraints but check out the hinge joint and give it full 360 degree of motion

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


# Question
Title: How can I change the direction of movement each time a key is pressed?
I would like change randomly the movement of an object every time I press Q.

It seems like the code should be like this, but it does not change the direction of movement as expected:

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

public class translate_random : MonoBehaviour {

    public float moveSpeed = 5f;

    void Update () {

        transform.Translate ( Time.deltaTime * moveSpeed, Time.deltaTime * moveSpeed,Time.deltaTime * moveSpeed);

        if (Input.GetKeyDown (KeyCode.Q)) {

            int random_trajectory_x = Random.Range (-10, 10);
            int random_trajectory_y = Random.Range (-10, 10);
            int random_trajectory_z = Random.Range (-10, 10);

            //aucun effet:la nouvelle transformation n'est pas appliquée
            //no effect: the new transformation is not applied.
            transform.Translate(
                       random_trajectory_x*Time.deltaTime * moveSpeed,
                       random_trajectory_y*Time.deltaTime * moveSpeed,
                       random_trajectory_z*Time.deltaTime * moveSpeed
            );
         }
    }
}

```

# Answer
Remember that `Update()` is called once each frame your game runs. Each time `Update()` is run, it's a completely separate operation from the last run. It has no memory or persistent state beyond what you save explicitly in variables.

So if you want `Update()` to remember your randomly-generated direction to keep moving in that direction next frame, and the frame after, then you need to save that information and read it to decide which way to move.

Here, we'll make a `Vector3` variable called `direction` to store the direction of travel. We'll make it a unit vector (always length 1), so our speed of movement is always exactly the value we provided via the `speed` field, and we don't speed up or slow down based on our random selection.

```
public class RandomMover : MonoBehaviour {
    public float speed = 5f;
    Vector3 direction;

    void Start() {
        direction = (Vector3.one).normalized;
    }

    void Update() {
        if(Input.GetKeyDown(KeyCode.Q))
            direction = Random.onUnitSphere;

        transform.Translate(direction * speed * Time.deltaTime)
    }
}

```
> 0 votes

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


title: Unity point light baking into lightmap

text:
# Question
Title: Unity point light baking into lightmap
I'm developing a puzzle with a ball with cracks on it. Inside the ball there's a point light. Its light rays come out of the cracks and hit some platforms (walls/ceiling/floor).

To solve the puzzle the player must rotate the ball to match the light coming out of the cracks with some pre-lit pattern on the platforms.

I don't know how to do the pre-lit pattern. I don't want it to be manually done using a texture editing tool like Photoshop or GIMP. I remembered this could probably be done using light baking. I think what I need is to bake the light from only that point light into a lightmap and use it only on those platforms, but don't know how to do that.

Can someone help me with a solution?

# Answer
> 1 votes
I've managed to implement two solutions for my problem.

1. Light baking
I set all surfaces where the light pattern was needed to 'Lightmap static'.
Then, duplicated both the point light and the ball with cracks (occluder), set them to 'static', set the light's 'Mode' to 'Baked' and the ball's 'Cast Shadows' to 'Shadows Only' (makes the mesh invisible but keeps its occluder properties).
To avoid the duplicate occluder to occlude the original light, I created a new Layer 'ShadowsOnly', set the duplicate occluder's layer to it and removed this layer from the original light's 'Culling Mask' (this will let the light from the original light to ignore the duplicate occluder).
2. Layer culling
I duplicated the light and occluder.
Set 'Cast Shadows' on the duplicate occluder to 'Shadows Only'.
Created a new layer 'ShadowsOnly' and 'Surfaces'.
Applied 'Surfaces' to my surfaces and 'ShadowsOnly' to the duplicate occluder.
Next, removed 'ShadowsOnly' from the 'Culling Mask' of the original light and set the duplicate light's to 'ShadowsOnly' + 'Surfaces' (makes the duplicate light only hit its occluder and the surfaces).

Both solutions worked for me and have some advantages and disadvantages over the other:

* The first (light baking) will guarantee a better performance since it's precomputed, unlike the second (layer culling) which is realtime.
* The second is easier to implement, understand, maintain and modify.

I would like to thank @DMGregory for the amazing help on the comments. Without him, I probably would've never done this. I hope this helps someone else too!

---
Tags: unity, lighting, lightmap
---


# Question
Title: issues about combo attack system animation
i have some issues about my attack animations right now, i'm doing my light attack which has 3 separate attacks and animations. the scripting and trigger works(without animation), but my animation just doesn't keep on playing from 1st to second to last attack, however, the boolean for the animator seems to work properly. i've set their transitions' interruption as "current state then next state". as i wanted to make the trigger "in sync" with the animation, i've set my boolean to false as the trigger disabled. I'm new with the animation, so i might need some advise for animating if avaliable edit: want to know if it's possible to refer other gameobject/children/parents in animation? as i would like to refer the trigger outside the object with animator component.

```
public class playerAttack : MonoBehaviour {
private bool attacking = false;
private bool heavyAttacking = false;
public KeyCode lightATK;
public KeyCode secondATK;
public KeyCode finalATK;
public KeyCode heavyATK;
private float comboResetTimer = 1f;
private int combo = 0;
private float comboTimer = 0f;
//private int attackcheck =0;

private float attackTimer = 0;
private float attackCD = 0.3f;
public Collider2D lightAttackTrigger;
public Collider2D comboAttackTrigger;
public Collider2D comboFinishTrigger;
public Collider2D heavyAttackTrigger;
public bool firstATK = true;
public bool SecondATK = false;
public bool thirdATK = false;

private Animator anim;

void Awake() {
    anim = gameObject.GetComponent<Animator> ();
    lightAttackTrigger.enabled = false;
    comboAttackTrigger.enabled = false;
    comboFinishTrigger.enabled = false;
    heavyAttackTrigger.enabled = false;
}

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

    if (firstATK)
    {
        if (Input.GetKeyDown(lightATK) && !attacking) {
            attacking = true;
            attackTimer = attackCD;
            comboTimer = comboResetTimer;
            combo += 1;
            firstATK = false;
            SecondATK = true;
            lightAttackTrigger.enabled = true;

        }

    }

    if (SecondATK)
    {
        if (Input.GetKeyDown(lightATK) && !attacking)
        {

            attacking = true;
            attackTimer = attackCD;
            comboTimer = comboResetTimer;
            combo += 1;
            SecondATK = false;
            thirdATK = true;

            comboAttackTrigger.enabled = true;

        }

    }

    if (thirdATK)
    {
        if (Input.GetKeyDown(lightATK) && !attacking)
        {

            attacking = true;
            attackTimer = attackCD;
            comboTimer = comboResetTimer;
            thirdATK = false;
            combo += 1;

            comboFinishTrigger.enabled = true;

        }
    }

    if (attacking) {
        if (combo == 1)
        {
            Debug.Log("nico");
            if (attackTimer > 0)
            {
                attackTimer -= Time.deltaTime;
                anim.SetBool("LightAttacking", true);
            }
            else
            {

                    attacking = false;
                    lightAttackTrigger.enabled = false;

              // anim.SetBool("LightAttacking", false);

            }
        }

        if (combo ==2)
        {
            Debug.Log("NICO");
            if (attackTimer > 0)
            {
                attackTimer -= Time.deltaTime;
                anim.SetBool("2ndLAttack", true);
            }
            else
            {

                    attacking = false;
                    comboAttackTrigger.enabled = false;
               anim.SetBool("2ndLAttack", false);

            }
        }

        if (combo == 3)
        {
            Debug.Log("NI!!!!!!!");
            if (attackTimer > 0)
            {
                attackTimer -= Time.deltaTime;
                anim.SetBool("FinalLAttack", true);
            }
            else
            {

                    attacking = false;
                    comboFinishTrigger.enabled = false;
                comboTimer = 0f;

                anim.SetBool("FinalLAttack", false);

            }
        }
    }

    if (comboTimer > 0) //count down tombo timer
    {
        Debug.Log("counting...");
        comboTimer -= Time.deltaTime;

    }
    else
    {
        combo = 0;
        //Debug.Log("Combo Reset");
        firstATK = true;
        SecondATK = false;
        thirdATK = false;

    }

        if (Input.GetKeyDown(heavyATK) && !heavyAttacking) {
        Invoke("heavyAttack", 0.5f);

    }
    if (heavyAttacking) {
        if (attackTimer > 0) {
            attackTimer -= Time.deltaTime;
        } else {
            heavyAttacking = false;
            heavyAttackTrigger.enabled = false;
        }

    }

}
void heavyAttack()
{
    heavyAttackTrigger.enabled = true;
    heavyAttacking = true;
    attackTimer = attackCD;
    Debug.Log("Heavy Attacked");

}

```

}

# Answer
so instead of linking these animation together, these attack animations should be transits with any state, with can transition to self unchecked
> 1 votes

---
Tags: unity, c#, animation, animation-controller
---


# Question
Title: How to create post-processing effects in Slick2D?
As I get closer and closer to the end of the feature development for my game and the beginning of the graphical overhaul, I keep thinking of ideas for graphical effects that would make my game even better, but Slick2D is so limited in terms of graphical capabilities. The LWJGL layer is exposed, and thus, basic OpenGL functions, but I don't know anything about the various blending functions and other functions available to me.

A couple of the most basic things I need to be able to do are to be able to properly blend images and primitive shapes together, and to be able to create a proper lighting system. As of right now, I simply have a black and white "stencil" for my flashlight that I blend with a flat black layer that's drawn over everything and set its opacity so it sort of looks like a flashlight. However, I'd like it to look better and to be able to have other light sources in the scene.

Also, I'd really like to be able to have "glow" effects, such as electricity or fire that brighten up the scene and don't just look like flat pixels. Is it as simple as additively drawing these images/shapes to the scene? Or is there more to it?

I know Slick2D is horribly outdated and no longer supported and I never should have used it, but it's definitely the last time I'll be using it. I only went to it because Java has limited game libraries available and LibGDX was giving me a lot of trouble getting started.

I'd appreciate any articles and examples.

**EDIT:** As an example of the "glow" effect, here's a neat explosion effect created in Unity that I found on /r/gamedev. It would be great if I could get something like this in my game.

https://www.reddit.com/r/gamedev/comments/8wurqc/stylized\_explosion\_shader\_breakdown/

# Answer
> 1 votes
slick2d shader's language is glsl so this tutorial is useful for you

but anyway I want to explain that how to make explosion effect that you added in your question.

**1.posterize noise texture**

> Posterization or posterisation of an image entails conversion of a continuous gradation of tone to several regions of fewer tones, with abrupt changes from one tone to another.
>
> https://en.wikipedia.org/wiki/Posterization

**2.use color palette and add to your Posterization**

this is a common way to add color to different level of Posterization that also used in celshading

example 1:

example 2:

**3.then use cut off to make cut based on your noise texture**

just use noise as alphaclip of your shader

this youtube tutorial will help you.

---
Tags: java, shaders, slick, post-processing, alpha-blending
---


title: how to duplicate a button via script?

text:
# Question
Title: how to duplicate a button via script?
I have the following code:

```
public GameObject characterButtonPrefab;
public GameObject characterButtonContainer;
public GameObject optionsContainer;

public GameObject[] charButtons;
private int charButtonsIndex = 0;
private Text[] cBT;
private string[] buttonTexts = new string[] {"Strength 5", "Agility 5", "Intelligence 5", "Charisma 5", "Diplomacy 5" };

private void Start()
{
    LevelIsOver = false;
    IsNextWave = false;
    //Time.timeScale = 1;

    for (int i = 0; i < charButtons.Length; i++)
    {
        int size = charButtons.Length;
        cBT = new Text[size];
        GameObject container = (GameObject)Instantiate(characterButtonPrefab);
        container.transform.SetParent(characterButtonContainer.transform, false);
        cBT[i] = characterButtonPrefab.transform.FindChild("Text").GetComponent<Text>();
        cBT[i].text = buttonTexts[Random.Range(0, buttonTexts.Length)];
        charButtonsIndex++;
    }

    //if (charButtons.Length > 0)
    //{
    //    GameObject currentChar = (GameObject)Instantiate(characterButtonPrefab);
    //    currentChar.transform.SetParent(optionsContainer.transform, false);
    //    currentChar.transform.SetSiblingIndex(0);
    //    currentChar.GetComponent<Button>().onClick.AddListener(() => CharacterSelection());
    //}
}

```

I declared the size of array to 20 in the inspector and everything work fine. The buttons are created and text changed. The question is how do I duplicate the first button in that array to another panel ? I have searched the internet but nothing found about this.

I have tried this:

```
GameObject currentChar = (GameObject)Instantiate(charButtons[0]);
     currentChar.transform.SetParent(optionsContainer.transform, false);
     currentChar.transform.SetSiblingIndex(0);
     currentChar.GetComponent<Button>().onClick.AddListener(() => CharacterSelection());
 }

```

But I get ArgumentException: The Object you want to instantiate is null.

# Answer
Supposing you have set the length of the `charButtons` in the inspector to 20, the default value of each element is `null`. You have to fill this array with instantiated buttons:

```
 int size = charButtons.Length;
 cBT = new Text[size];

 for (int i = 0; i < charButtons.Length; i++)
 {
     charButtons[i] = (GameObject)Instantiate(characterButtonPrefab);
     charButtons[i].transform.SetParent(characterButtonContainer.transform, false);
     cBT[i] = characterButtonPrefab.transform.FindChild("Text").GetComponent<Text>();
     cBT[i].text = buttonTexts[Random.Range(0, buttonTexts.Length)];
     charButtonsIndex++;
 }

 if (charButtons.Length > 0)
 {
     GameObject currentChar = Instantiate(charButtons[0]);
     currentChar.transform.SetParent(optionsContainer.transform, false);
     currentChar.transform.SetSiblingIndex(0);
     currentChar.GetComponent<Button>().onClick.AddListener(CharacterSelection );
 }

```
> 0 votes

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


# Question
Title: Why it isn't possible to get a progress in SceneManager.LoadSceneAsync between 0.0 and 0.9?
I am trying to understand why does SceneManager.LoadSceneAsync progress always jumps from 0.0 to 0.9, no matter how big a scene can be.

To try trigger smoother `progress` of the scene being loaded, I've tried the following:

Generate a large scene from an `EditorWindow`, containing tens of thousands of objects referencing thousands of assets. Loading this scene didn't produce the intended behavior, rather, it ended up being exactly the same (jumps from 0.0 to 0.9) but with a huge lag at the end since there are many objects.

According this behavior, I am now considering that the supposed asynchronicity in `SceneManager.LoadSceneAsync` is just about the loading of the scene file itself, not processing its content for being usable by Unity.

Is this correct?

An example on how to load a large scene and report its progress would be appreciated :)

# Answer
A while Back CodeMonkey a youtuber has posted a video tutorial for scene manager, there i find this comment from a random guy named Rick Loyd who says
*I faced that issue and the only solution I found was to implement loading yourself. Anything you load from code (the way you like to do it), Unity unable to detect and therefor ignores. From my own experiments, the whole loading shows only loading of resources... but neither awake, nor start methods are called until 90%... so basically when you load everything yourself from resources, this code will be executed only after scene gets activated, after 90%. The kind of solution I though is to load resources within loading class and keep them as "do not destroy" until scene you needs gets loaded... however, unity still do not care about that, so you need to give 50% loading to your own code, and 50% to unity loading or make two progress or load progress twice (I have seen such solutions in games too)*

Here is the video link

You will find a very good discussion of `LoadSceneAsync()` in the comment section, check out very first comment pinned by codemonkey.

Lastly Yes this is not a good answer, I know that but I only posted it as an answer because it exceeds the comments allowed letters limit
> 1 votes

---
Tags: unity, loading, scene
---


title: Unity 2D rigging parts order

text:
# Question
Title: Unity 2D rigging parts order
Hello I have some 2d character in sprite I've rigged to use in Unity 2D.Something like this, with separate body parts.  Although I've used weights and geometry, these body parts are supposed to move independent of each other, so there is no stretching/blending (or whatever you call it) of the shapes/body parts. Now I've created the rig successfully, I realize that these body parts are no at the order I want, meaning some parts are overlapping others in the wrong order. How should I fix that?

# Answer
> 2 votes
It's really simple, but Unity changed the interface recently so most of the tutorials weren't helpful and I didn't know what keywords to look up.

So if you click on the sprite image in the asset folder, go to Sprite Editor in the Inspector, then click on skinning editor (at the top left corner), and then you double click on the image for the bones to show. And then click on a bone, and it allows you to edit the depth of each bone. So that's it.

# Answer
> 0 votes
you would want a seperate game object in the scene for each part. You can use the "order in layer" property on the sprite renderer, or the z value to determine what draws on top of what. You should build your character has a hierarchy of sprites, and use the parent/child relationship to make the objects pivot how you like. For example you can have

```
bodySprite
  shoulderJoint
    armSprite

```

In this case body sprite is the body, shoulder joint is located where you want the arm to connect, then the arm is a child of the shoulder joint, and you offset it down so the top of the arm connects with the shoulder. Now if you rotate the shoulder joint, the arm rotates around the shoulder.

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


# Question
Title: Unity is single thread then why unity webgl says asset bundles are load in main thread
Got stuck in a performance issue in Unity WebGL that whenever my asset bundles are load, my unity game gets freeze for some seconds/minutes. I know that unity is not thread-safe and it is based on a single thread but these statements are confusing for me. From the official sites/persons of unity:

> Threads are not supported due to the **lack of threading supporting in JavaScript**. This applies to both Unity’s internal use of threads to speed up performance, and to the use of threads in script code and managed DLLs. Essentially, anything in the System.Threading namespace is not supported (Source Unity Docs 1).

Lack of threading support in JS? Does it mean it supports on the desktop?

> Since WebGL does not support threading, and since HTTP downloads will only become available when finished, Unity WebGL builds need to decompress AssetBundle data on the main thread when the download is done, thus blocking the main thread. To avoid this interruption, you may want to avoid using the default LZMA Format for your AssetBundles, and compress using LZ4 instead, which is decompressed very efficiently on-demand. If you need smaller compression sizes then LZ4 delivers, you can configure your webserver to gzip-compress the files on the http protocol level (on top of LZ4 compression) (Source Unity Forum/Offical 2).

**Here is saying doesn't support threading but the asset bundle is load in the main thread? Do it support thread? It sounds confusing to me**.

> WebGL does not support threads, so the Async operation is running on the main thread causing the freeze that you are seeing (Source Unity Forum/offical). Blockquote

Doesn't support thread but asset bundle loading in the main thread??

These statements are confusing for me? Do unity supports thread? If Not then, What is the `main thread`? Why unity repeatedly call that asset bundle is load in main thread? If unity doesn't support thread then how async/coroutine operation is performed?

Edit: **Unity 2019.1 has released with this note WebGL: Added experimental multi-threading support. Do it means we can use thread now?**

List of issues in unity-WebGL.

# Answer
Unity does run multiple threads, but NOT in WebGL.

1. Standard unity and most of it's target platforms that support multithreading will use multithreading. If you've ever had your game freeze and heard the audio continue to play, that's why. There's an audio thread, a render thread, a game logic thread, and I think a physics thread (but I'm not 100% on that). Concurrent game engine design is a complicated topic as I'm learning while building my own engine, so I won't explain how each of the threads work. What's important to know is you only need to work within the main thread. You can in fact write multithreaded libraries as long as you don't call unity functions. For example I wrote a library for parsing joycon input via bluetooth. This library runs on a seperate thread recording and time stamping inputs, then in Unity's update cycle, asks the joycon thread what inputs have come in.
2. Unity's WebGL support is... lacking. While porting a major project over, I experienced many pains. For one, it does not handle audio correctly at all. Usually in audio your sound card is capable of outputting X number of voices at once. In other words, X distinct sounds. But many games have more than X sounds, so unity will mix sounds together into a single sound, and sometime just not play a sound all together. This is what the priority field in an audio source does. In WebGL it supports none of this, and if you play too many sounds at once, the audio will crash. Try writing a script that plays X audio sources at once. Increase X, build, run on browser of choice. Depending on browser and computer, that number will differ. The lowest I ran into was macbook. If you have many sounds in your game (like a bunch of units/characters screaming into battle) then you will have to write your own system, which is a lot of work. WebGL as you gathered also does not support multi threads.
3. Asset bundle are basically necessary for WebGL. In a standard environment, you save the game on disk, then when you run, you load the required resources into RAM for quick access. In WebGL you ONLY have RAM. And you only get ~1GB. You can go more but you'll have compatibility issues fast. If you're making a game from scratch, plan for this. I advise making each scene an asset bundle. You can use unity's AssetBundleBrowser to do this. The docs are pretty inaccurate, but it will include the dependencies when you bundle it. If found the "build" button didn't work, so you can write your own script for it. I'll leave out the details because it's all easily googlable information, but it's hard to find what DOES and DOESN'T work, so I'm just describing my rough process. From there make sure each scene is less than ~750mb. Unity will need some space to run, and uses up some of your precious memory. If you're porting, you may have to compress the ever loving fuck out of your assets. Audio and visual. Follow unity's webGL guide for the type of compression. You can then use the loading screen to get your asset bundle. Use the AssetBundle API not WWW because WWW will load double the amount of memory, since it will download, THEN decompress. AssetBundle will decompress as it downloads, minimizing the memory spike. I can't put all the pitfalls of asset bundles in one response, but hopefully this will help with some of the more difficult problems I faced. Don't forget to keep track of how many audio sources you're playing.
4. Finally, after all this, if you're not tied to Unity, I'd advise simply not using it for Web content. If you're starting a new project, and have little investment in Unity, go learn an engine designed for web. There's lots of JS game engines out there that will have far better support. WebGL in Unity is the forgotten child that gets kept in the basement. I'd avoid it if you can. But if like me, you find you have to, get ready for a long and tough ride.
> 4 votes

# Answer
What Unity doesn’t support in JavaScript is *multiple* threads. So there is only ever the single main thread of execution. If there were multiple threads, Unity would be able to run LZMA decompression on a background thread while the main thread is busy running the game. However, since this is not the case, it must apparently use the only thread of execution available, which cannot run the game during this time.

Coroutines are not implemented using threads, even when multiple threads are supported. Coroutines always run on the main thread. They use a special feature of C# (“yield return”) which lets you pause execution of a method and come back to it later. So Unity keeps track of all the coroutines it’s running, and goes back into them at the right time. A simple implementation of how Unity does it internally might look like this:

```
mainLoop() {
    while (true) {
      runUpdates();
      runCoroutines();
      renderFrame();
    }
}

runCoroutines() {
  for (coroutine in coroutines) {
    coroutine.MoveNext();
  }
}

```

Where `MoveNext` is the method that goes back into the coroutine’s code and executes it until it reaches the next yield instruction, at which point the coroutine temporarily suspends execution until the next call to `MoveNext`.
> 1 votes

---
Tags: unity, c#, assetbundle, thread, async
---


# Question
Title: Is it feasible to create a game in godot using little to no GDScript
I am trying to get more into game development, I have very little experience with it. I've been messing around a bit with the Godot engine and am slowly starting to understand it more. I have some experience with C# and C++, both of which can be used with Godot (to my knowledge, correct me if I'm wrong), and it also has its own language, GDScript. From what I've seen the language looks a lot different from any I've used (C#, C++, and Java), and I really don't want to learn it, I especially don't want to learn a new engine and a new language at the same time.

So basically would it be possible to create a game in Godot using very little to no GDScript without missing out on features or making life a whole lot harder? Another way to word it could be 'is there any thing that is impossible or very much harder to do in C# or C++ than if you were using GDScript?'

Sorry if this is too broad or anything, I'll try to fix it if need be

# Answer
Godot can be used fully without any type of GDScript interaction.

C# has official engine support, and can be used instead of GDScript in all places because the way C# scripts are loaded is similar. In fact, all of the "built-in" functions available in GDScript are made available in C#, typically as static methods under `Godot.GD`. I personally have had a very smooth experience with Godot Mono, and recently competed in a Game Jam using only C#, no GDScript at all, without any issues. On a personal project of mine, the only time knowledge of GDScript became an issue was when I imported a plugin for an in-game dropdown console which I wanted to bind to my C# scripts (and fix as well because it was very broken at the time of writing this). However in my case I come from a Python background, so GDScript was very familiar to me. In your case, it may not be worth using GDScript plugins, but it's completely up to you.

C++ is a completely different monster that I cannot speak much about, but any C++ must be compiled with the engine as a module and does not support scripting in the same way that C# and GDScript do, but it's the option many people still take so go for it.

Overall, the answer is yes, you can build complete games without touching GDScript. **Most** examples in the official documentation offer both GDScript and C# snippets.
> 4 votes

# Answer
*Note: I am not an expert in the Godot engine and have only used it on occasion*

The Godot engine should be just fine for building a solo project from scratch with little to no coding. Godot does support C# and C++ for some instances where you want to implement a niche feature/idea for your game, and it should be fine to just learn their visual editor beyond that.

Godot is a nice middle tier engine: a bit more handholdy and easy to start with than Unity3D/Unreal, but more advanced than RPGEngine. Nothing is wrong with starting out with any of these, in fact I would say that the best thing to do as a burgeoning gamedev is to *just pick one* and go with it.

**TL;DR**: It looks great to start out with, get going!
> 0 votes

---
Tags: c#, c++, godot
---


# Question
Title: Start a progress bar when clicking a button
This is basically what i am trying to do:

1. Click first scene-\>Button
2. Start A Progress Bar
3. When the Progress Bar finishes, then...
4. Second Scene-\>instantiate my Game object

This is my code:

```
// First Scene
public class LoadingScreen : MonoBehaviour  //first scene script
{
    public GameObject slidercanvas;

    public void NextScene()
    {

        StartCoroutine(LoadNextLevel());
    }
    IEnumerator LoadNextLevel()
    {
        slidercanvas.SetActive(true);
        Slider s = slidercanvas.GetComponentInChildren<Slider>();
        AsyncOperation sceneLoading =SceneManager.LoadSceneAsync("ScrollGrids");

        while (!sceneLoading.isDone)
        {
            float progress = Mathf.Clamp01(sceneLoading.progress / 0.9f);
            s.value = progress;
            yield return null;

        }
   }

  //second scene

  public class ScrollGridScript : MonoBehaviour
  {
    public static ScrollGridScript Instance;
    public GameObject SpawnPrefab;
    GameObject newobj;
    public GameObject parent;
    Vector3 pos;
    string msgSpeech;
    int counter=0,totalVal;
    public List<GameObject> btns;
   //float progress;

    void Start()
    {
        btns = new List<GameObject>();
        StartCoroutine(Populate());
    }
    void Update()
    {
        if (totalVal==counter)
        {
            for (int i = 0; i < btns.Count; i++)
            {
                btns[i].SetActive(true);
            }
        }

    }
    IEnumerator Populate()
    {
        //code here(encoding jsonurl)
        StartCoroutine(Downloadimage(newobj, msgSpeech,tname));
        totalVal =  data["categorylist"].Count;
    }

    public void OnButtonclick(string imgname)
    {
        effector.Instance.setEffector(imgname);
        Debug.Log("ButtonId" + imgname);
    }

   IEnumerator Downloadimage(GameObject newobj, string imgUrl, string catid)
   {
      UnityWebRequest www = UnityWebRequestTexture.GetTexture(msgSpeech);

      DownloadHandler handle = www.downloadHandler;
      yield return www.SendWebRequest();

      Texture2D texture2d = DownloadHandlerTexture.GetContent(www);

      if (www.isHttpError || www.isNetworkError)
      {
            UnityEngine.Debug.Log("Error while Receiving: " + www.error);
      }
      else
      {
       counter++;
       newobj = (GameObject)Instantiate(SpawnPrefab, pos, Quaternion.identity);
       newobj.transform.SetParent(parent.transform);
       newobj.transform.localPosition = pos;
       newobj.GetComponent<Button>().onClick.AddListener(() =>
       OnButtonclick(catid));
       Image sprite = newobj.transform.GetComponent<Image>();
       sprite.sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width,
       texture2d.height), new Vector2(0, 0)); //fetch the images from the serve
       //and convert it
       newobj.SetActive(false);
       btns.Add(newobj);  // instantiate object store in list
    }
}

```

And here is the output I see when I run this code:

# Answer
You can use Async Scene Loading. This will try to load the scene and at the same time, you can show the slider. Below is an example script you can use.

1. So when the button is pressed We will start the co-routine by "StartCoroutine(LoadNextLevel())".
2. Then in some scripts inside your "scene2", you should instantiate your game object in the Start() Method Or inside "SceneManager.sceneLoaded" delegate

```
// Starts a Progress Bar and Loads the next scene asynchronusly
IEnumerator LoadNextLevel()
{
  sliderCanvas.SetActive(true); // show the progess bar
  Slider s = sliderCanvas.GetComponentInChildren<Slider>(); // grab the progress bar slider
  AsyncOperation sceneLoading = SceneManager.LoadSceneAsync("Scene2");// try to load next scene

  while (!sceneLoading.isDone) // keep increasing the slider value until the next scene is loaded
  {
    float progress = Mathf.Clamp01(sceneLoading.progress / 0.9f);
    s.value = progress; // assign the sliders value with scene load progress
    yield return null;
  }
}

```
> 1 votes

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


# Question
Title: Displaying pixels on a canvas at 60 hertz
I'm (new to SO and) attempting to code an "emulator" for an 8-bit CPU I am making with a friend. I have only ever used Java to make simple GUIs with Swing, and from reading similar questions it seems to me that using repaint() and Graphics2D to display 60fps is not the way to go.

From my attempts at using a custom JComponent to draw, I couldn't agree more. Despite calling screenComponent.repaint() 60 times per second, Java was only updating the screen around 2 times per second, whereas the video memory byte array (stores pixel data) that was also updated 60 times per second (before calling repaint) did change every frame.

So my question is: what can I use to display my one-dimension pixel array (using y * width + x to get pixels at a coordinate) and update it at 60fps?

What I need to be able to do:

1. draw each individual pixel with a set color -draw text with a font and size (the computer I am emulating has a toggle able text-only graphics mode)
2. efficiency is not a huge concern since the main purpose of this is to test assembly programs that will later run on the physical CPU, but it needs to update the screen at 60 Hertz and run CPU clock cycles at least at 1 kilohertz
3. scale up the canvas as the cpu only displays at 78 by 128 pixels (I did this in swing by using g2d.fillRect to display pixels and multiplying the arguments by a screen size multiplier integer)
4. not 3D

# Answer
Try something like LibGDX, JSDL or JSFML and render pixel-plotted results to a fullscreen texture.

These are mentioned because you ideally want an existing, fast 2D pixel plotter founded on an API like OpenGL, that provides hardware rendering support; because even though you don't need 3D, you *do* need fast draw access. And you need Java bindings.
> 1 votes

# Answer
I eventually figured it out, using libGDX as @Engineer suggested. The trick was to use a Pixbuffer object and write it to a Texture, then call buffer.draw on the texture every time a frame is rendered.

Setting up libGDX was also a bit tricky as I am not familiar with Gradle and prefer to use NetBean's compiler instead. I had to import the correct jars from a nightly build of libGDX as the setup tool offered insists on using Gradle. It was relatively easy to use afterwards, which is really nice.

For reference, I believe I just imported: gdx, gdx-natives, gdx-backend-lwjgl, and the font extension so I could load my text font and scale it according to the screen size.

I (think?) I accepted Engineer's answer and upvoted it, although I believe my vote doesn't count due to my low reputation. Whoops.

Here's a screenshot of the window in action:
> 0 votes

---
Tags: java, rendering, emulation
---


# Question
Title: How to control jump strength by how long the player presses the jump button?
In a platformer game I am working on, I want my character to have controlled jumps. If I simply tap the jump key it will jump a just a little or if I hold it for a time it will jump higher.

What do I need to do?

# Answer
> 6 votes
You have essentially 2 options. You can either apply a constantly decreasing force to the character while the player is pressing the space button and stop immediately when they release it or apply a higher force of gravity when the player releases the space and go back to normal gravity, when the jump reaches the peak. For instance, the first Super Mario Bros used the latter.

The first option is in my opinion a lot more intuitive and gives you a nicer curve, but the latter can be a little more responsive and gives you better control over the jump height.

The former is also harder to get right in a game design perspective, since instead of defining a max jump height, you only set the minimum.

Implementing both is fairly easy, for the first one you'll need to store the current jump force somewhere. Pseudo code

```
jumpForce = 10
jumpDampening = 0.8 // This determines how much the jump force weakens every frame.

// Later
if (jumpKeyDown) {
    player.velocityY += jumpForce
    jumpForce *= jumpDampening
} else {
    jumpForce = 10
}

// Apply gravity

```

The other one needs to detect when the jump reaches it's peak too:

```
normalGravity = -9.81
stoppingGravity = -30
jumpForce = 30

// Later
if (playerIsOnGround && jumpKeyDown) {
    player.velocityY += jumpForce
}

// Apply gravity based on whether the jump reached it's peak yet
if (!jumpKeyDown && player.velocityY > 0) {
    player.velocityY += stoppingGravity
} else {
    player.velocityY += normalGravity
}

```

Side note:

If you want to get a "tighter" jump, then always apply the stronger gravity when the player isn't holding the jump button. This will let the character fall to the ground faster, resulting in more control.

---
Tags: platformer, control, jumping, godot
---


title: Activate specific element In Array?

text:
# Question
Title: Activate specific element In Array?
In my array there are 6 elements "guns" and I want to activate one element after deactivate all of them. Here is my script

```
public saveInfo _file; // get gun ID number from save file.
public GameObject Player1_pistol;
public GameObject[] pl1_p; // 6 guns

void Start()
{
    pl1_p = new GameObject[Player1_pistol.transform.childCount];
    for (int p = 0; p < Player1_pistol.transform.childCount; p++)
    {
        pl1_p[p] = Player1_pistol.transform.GetChild(p).gameObject;
        pl1_p[p].SetActive(false);
      // Now I need to activate the third element in my array.
    }
}

```

# Answer
> 1 votes
You can solve this by getting the number from the save file and use it inside for function or outside it.

```
// inside for function
        pl1_p[p].SetActive(p == "get number from save file");
// outside
        pl1_p["get the number from save file"].SetActive(true);

```

Good luck.

---
Tags: unity
---


# Question
Title: Understanding constant acceleration in terms of game physics simulation
There are various integration methods that can be used for games. I am trying to write a simple physics engine deciding between semi-implicit Euler and Verlet variants.

What I don't understand is where most information says that they work well for **constant acceleration**. Say more than one force acts on a body, and acceleration is calculated using force/mass. Velocity and position are derived from this. This means that the acceleration is not constant surely?

Am I incorrect in my understanding that applying a force in one step, and a different force at another step, is variable acceleration? Is it simply that the error amount is small enough to be ignored. So semi-implicit Euler, with fixed time-step but variable acceleration, for example, will be a good approximation?

I'm very confused, I've read so many different things. I'd appreciate any insights. Thanks!

# Answer
> 4 votes
In your context, I think **constant acceleration** refers to acceleration's like Earth's gravity. This is lengthy because you are not specific about how you are using the model. Are you trying to simulate gravity, space travel, bullet riccochet, etc?? I'm kind of a math-nerd and would be happy to reply with more specific detail if you are more specific about your application. I chose gravity for my explanation because I'm also a space-nerd, but understand that everything below is generally applicable to all forms of physics interaction.

In general, unless acted upon by an additional force, any two objects will accelerate toward **each other**, in proportion to their masses. Since most objects' masses are trivial compared to a planet, the impact of the object on the planet itself is usually ignored. Since the mass of planets does not frequently vary, acceleration due to gravity is considered a "constant".

Integration for motion of an object:

```
Velocity += (Acceleration * elapsedSeconds);
Position += (Velocity * elapsedSeconds);

```

To model a stationary object free-falling to Earth from any starting distance:

```
Acceleration = (0, -1, 0) * 9.8f; //Earth's "constant" gravity at sea level

```

When Position.y falls below 0, the object has landed. The position is at or below the surface and may need to be corrected to the actual ground height. While correcting the location, you need to do something with the remaining velocity at the time of impact. You can just discard it by setting Velocity to 0 or, using the objects' mass and velocity, calculate the specifics of the impact and apply the resulting accelerations to the objects for the next Update().

# Short term

In terms of precision/error, you will have no problem drawing something believable and glitch-free on the screen. If you need even more precision, you can store and transform your vectors using double-precision, and casting the resulting (more precise) vector to a regular Vector3 only when you actually need to feed it to DirectX.

# Long term

Even with a custom DVector3 (Double-precision Vector3) structure, if you digitize an epoch and then run any significant amount of time, eventually divergence manifests and your model becomes incorrect. This actually happens in real life, as well; each epoch defined and used as a basis for measurement, (with our current level of technology) ALWAYS has an expiration date for the very reason you are facing.

```
Velocity += (Acceleration * elapsedSeconds);

```

When you do this, you are summarizing all of the billions of billions of interactions that happened within elapsedSeconds to a single "most-significant" value.

# For orbital motion

```
Acceleration = PullFromSun;      //=
Acceleration += PullFromMoon;    //+=
Acceleration += PullFromMercury; //+=
...
Velocity += (Acceleration * elapsedSeconds);
Position += (Velocity * elapsedSeconds);

```

# For bullet travel

When first fired,

```
Velocity = {arbitrary bullet speed vector};
Acceleration = Gravity;  //bullet drop

```

Then,

```
Velocity += (Acceleration * elapsedSeconds);
Position += (Velocity * elapsedSeconds);

```

until colliding with an object (including the terrain) and/or a new position is calculated that is out-of-bounds/off-the-screen/out-of-range.

# Multiple interactions

This is as difficult as you want. You *could* integrate all colliding objects' Accelerations until the collision is mathematically complete and the system comes to rest with all objects having Acceleration equal to Gravity and Velocity equal to 0. This is what the universe does.

Instead, just summarize (with as much complexity as you require) the entire collision at the time that it occurs. Minimally, an object that hits another object should impart a portion of its Velocity to the object(s) that were hit.

```
Velocity += (CollidingObjectsMass * CollidingObjectsVelocity) / (Mass + CollidingObjectsMass)

```

# Summarizing interactions

This will provide realistic results for most mass-dependent transfers (collisions):

```
AnyFactor += (InteractingObjectsMass * InteractingObjectsAnyFactor) / (Mass + InteractingObjectsMass)

```

When that isn't good enough, the inverse-square law is probably more relevant. To model the gravitational force the Sun(Object2) exerts on the Earth(Object1):

```
Direction = Object2Location - Object1Location;
Magnitude = GravitationalConstant * (Object1Mass * Object2Mass) / (Direction.Length ^ 2);

```

When calculating the first (or only) object, use '='. This is the same as the free-falling-object calculation above with Direction pointing to Earth's center and Magnitude being explicitly specified as 9.8.

```
Acceleration = Normalize(Direction) * Magnitude;

```

Because the Sun is soooooo far away, its pull on an object on earth at sea level, is negligible, compared to that of the Earth, itself, so in earth-gravity-only models, it is ignored. If you wanted to model the solar system, though, for each object after the first, use '+='

```
Acceleration += Normalize(Direction) * Magnitude;

```

Then, the usual

```
Velocity += (Acceleration * elapsedSeconds);
Position += (Velocity * elapsedSeconds);

```

To **accurately** model **just** Earth's trajectory, you would need to digitize the entire universe and be able to time-integrate the entire thing, precisely. Instead, when simulating the universe, it is divided into compartments called barycenters. Our solar system is usually thought to be centered on the sun. Although effectively true, that is technically false. If you averaged the mass, density, location, velocity, and every other property of everything within our solar system into a single mass, it's location would be near the **surface** of the sun, not at its' **center**. An hour later, the barycenter's center has moved.

# Barycenter's are as infinitely-scalable as the universe is deep

Consider that the earth is composed of many different materials with many different properties, but all of those materials move and rotate around a common center point, a barycenter by definition. We are affected by every individual particle that comprises the earth, separately, yet we refer to Earth, mathematically, as a single entity with a single, constant gravity value. That's because, over time and, on average, all of Earth's properties continually produce a "constant" amount of gravity at sea level. We average particles into planets, planets into solar systems, solar systems into galaxies, etc, etc.

If you calculate the barycenter for our solar system but leave Earth out of the calculations, you can accurately model Earth's orbit with one calculation.

```
EarthsVelocity += (AccelerationCausedBySolarSystemWithoutEarth * elapsedSeconds);

```

The problem is that your model will not remain **technically accurate** unless you recalculate the barycenter each frame, defeating the time saved by using them. Recalculating everything every time would produce truely **variable acceleration**.

If you forego technical accuracy right off the bat, it's trivial to recalculate the Earth-less barycenter using time-integrated distance and Euler angles for everything, every frame. Interacting the Earth with the resulting barycenter will produce an accurate, albeit made-up, gravity-based, orbit. Using Euler's prevents a lot of error from accumulating in the solar system, itself, while allowing the Earth to actually traverse it based on "real gravity". All of which can be used to produce cyclical weather, temperature, etc. patterns.

# Answer
> 0 votes
Notice how accelleration is just assigned every frame independantly. Thats as good as saying the physics engine doesnt bother with accelleration as a kept register, its just the bin you apply the forces to.

---
Tags: mathematics, physics-engine, integration
---


# Question
Title: How to handle jumping up a slope in a runner game?
In an 2D endless runner, what should happen when the player is running "too fast" up a slope and jumps?

For example, in a "normal" case:

```
    .O.
   . __..O_____
  . /
 . /
 O/
_/

```

If he is moving to the right slowly enough, he will jump upwards and land on the flat part of the surface. However, if he is moving too fast, the jump will have no effect as his forward motion will bring him back in contact with the slope before he can get high enough to pass over it. When the speed is sufficiently high, there will effectively be no jump.

```
     _________
    /
 .O/
 O/
_/

```

Are there any known ways to solve this issue? I know it's physically correct\*, but are there techniques that other games use to overcome this in a reasonable manner?

As a last resort I'll have to just remove all slopes that are too slanted.

\*If you constrain the player to never jumping backwards.

# Answer
Here are some examples of how games (runner or otherwise) have handled this situation. There is no "best" and you still have to decide which one is right for your game.

## The physically "correct" way (vertical impulse)

To jump, you add a **vertical impulse (red)** to your **movement velocity (green)**. The **resulting velocity (blue)** will always take you above the slope, so as long as your slope doesn't get too much steeper soon, your character will always jump above the slope.

The caveat is that if your character is racing up a steep slope, you can now jump up very high.

## Perpendicular jumps (Sonic)

When jumping, your jump impulse is in a **direction (red)** perpendicular to the **slope (green)**. You may remember this behaviour from the Sonic games.

The caveat is that on very steep slopes, you often end up jumping backwards.

## No jumping on slopes

Maybe you decide that slopes are kind of special and it doesn't make sense to jump on them. For example, stairs are a special kind of slope, which in some games you can't jump on at all.

The caveat is that, whenever you take away control from the player like this, you need to clearly communicate the expectations, otherwise the player can get frustrated. For example, Castlevania uses a special "stair climbing" animation to make it clear that it's a special kind of motion.

## No running on steep slopes

Another option is to make it impossible to climb slopes that are too steep - players slide down as if it's a wall-like obstruction. Since they are falling or sliding down, it's clear that they can't jump during this time either.

## No steep (up)slopes

You could take the easy way out and entirely remove slopes that will give you such problems. This is not as bad an idea as it sounds, because walking up slopes is no fun; walking down slopes is way more exciting!

## No slopes (the Mu answer)

When it comes to gameplay, I'm a fan of minimalist design - as the saying goes, "perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away". Do slopes serve a useful gameplay purpose, or do they just look good - i.e. are they *fun*? After all, it's perfectly fine to have a runner with no slopes at all.
> 12 votes

# Answer
For anyone else who comes across this, I got around it by having a minimum number of frames that must pass in the jump animation before collision with the hill is registered. That way you have a grace period to allow the character to get up a little bit without worrying about the slope collision.
> 1 votes

# Answer
the raycast is a good idea,you may use ray judge whether it is a slope ,then you can controll the velocity by changing the player velocity.
> -1 votes

---
Tags: physics
---


# Question
Title: How to scale a sprite on x axis to touch the point without changing pivot?
I have a sprite. The pivot is at random point.

I want to increase the sprite's scale on the x axis, without moving the pivot, until its edge touches a point at right.

I have a method to set/add size. I calculate a distance from the sprite's edge to the point at the right and add it as a size.

The problem is the sprite scale increases its size in both directions of the x axis (left and right), considering the pivot is not at the left edge of the sprite.

How can I scale the sprite while keeping the left edge where it is?

I have:

I want to get:

# Answer
> 0 votes
I solved the problem. The next method sticks a right side of a gameobject to the point on x axis:

ScaleToStick:

```
private void ScaleToStick(GameObject gameObject, Vector3 target)
{
    Bounds bounds1 = StaticScript.GetBoundsChildren(gameObject);
    float size = target.x - (bounds1.center.x + bounds1.extents.x);
    float distancePivotToCenter = bounds1.center.x - transform.position.x;
    float _1 = distancePivotToCenter + bounds1.extents.x;
    float _2 = distancePivotToCenter - bounds1.extents.x;
    _2 = Mathf.Abs(_2);
    float x = (_1 + _2) / _1;
    size *= x;

    StaticScript.AddSizeUniform(gameObject, size, "x");
}

```

GetBoundsChildren:

```
public static Bounds GetBoundsChildren(GameObject gameObject)
    {
        Bounds bounds = new Bounds();
        bool first = true;

        foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
        {
            if (first)
            {
                first = false;

                if (renderer.bounds.size == Vector3.zero)
                {
                    Bounds bounds_ = new Bounds();
                    bounds_.center = renderer.gameObject.transform.position;
                    bounds = bounds_;
                }
                else
                    bounds = renderer.bounds;
            }
            else
                if (renderer.bounds.size == Vector3.zero)
            {
                Bounds bounds_ = new Bounds();
                bounds_.center = renderer.gameObject.transform.position;
                bounds.Encapsulate(bounds_);
            }
            else
                bounds.Encapsulate(renderer.bounds);
        }

        return bounds;
    }

```

AddSizeUniform:

```
public static void AddSizeUniform(GameObject gameObject, float sizeAdd, string axis)
    {
        Vector3 scaleOld = gameObject.transform.localScale;
        Vector3 sizeOld = GetBoundsChildren(gameObject).size;

        Vector3 scaleNew = Vector3.zero;
        float scaleNewMultiply = 0;

        if (axis == "x")
            scaleNewMultiply = (sizeOld.x + sizeAdd) / sizeOld.x;

        if (axis == "y")
            scaleNewMultiply = (sizeOld.y + sizeAdd) / sizeOld.y;

        if (axis == "z")
            scaleNewMultiply = (sizeOld.z + sizeAdd) / sizeOld.z;

        scaleNew.x = scaleNewMultiply * scaleOld.x;
        scaleNew.y = scaleNewMultiply * scaleOld.y;
        scaleNew.z = scaleNewMultiply * scaleOld.z;

        gameObject.transform.localScale = scaleNew;
    }

```

---
Tags: unity, mathematics, sprites, scale
---


# Question
Title: vkCmdCopyBuffer has no effect for transfer of staging buffer
for a vulkan renderer using vulkan-hpp and Vulkan Memory Allocator I am trying to transfer vertex data to the gpu using a staging buffer. Without using an intermediary staging buffer the transfer works and the meshes can be rendered with no problems (just a single buffer created with VMA\_MEMORY\_USAGE\_CPU\_TO\_GPU). But with the call to vkCmdCopyBuffer the resulting vertexBuffer only contains 0s (checked with NSight). Thinking that synchronisation using barriers might be required I tried the following code, but still have the same problem.

Maybe there is a need to synchronize the command buffer doing the copy with the later command buffer binding and sourcing from the vertex buffer? Although I didnt see this done or mentioned in any tutorials I came across.

```
// vulkan initialization
// VmaAllocator initialization

std::vector<Vertex> vertices = { /*filled*/ };
auto vertexBufferSize = vertices.size() * sizeof(Vertex);

vk::Buffer stagingBuffer;
auto ci = vk::BufferCreateInfo().
    setUsage(vk::BufferUsageFlagBits::eTransferSrc).
    setSharingMode(vk::SharingMode::eExclusive).
    setSize(vertexBufferSize );
VmaAllocationCreateInfo allocationCI = {};
allocationCI.usage = VMA_MEMORY_USAGE_CPU_ONLY;
vmaCreateBuffer(allocator, (VkBufferCreateInfo*)&ci,
    &allocationCI, (VkBuffer*)&stagingBuffer, &allocation, nullptr);
void* pVBufMem = nullptr;
vmaMapMemory(allocator, allocation, &pVBufMem);
std::memcpy(pVBufMem, vertices.size(), vertexBufferSize );
vmaUnmapMemory(allocator, allocation);

vk::Buffer vertexBuffer;
ci = vk::BufferCreateInfo().
    setUsage(vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eVertexBuffer).
    setSharingMode(vk::SharingMode::eExclusive).
    setSize(vertexBufferSize);
allocationCI = {};
allocationCI.usage = VMA_MEMORY_USAGE_GPU_ONLY;
vmaCreateBuffer(allocator, (VkBufferCreateInfo*)&ci,
    &allocationCI, (VkBuffer*)&vertexBuffer, &allocation, nullptr);

// copy staging buffer to vertex buffer
auto allocCI = vk::CommandBufferAllocateInfo().
    setCommandBufferCount(1).
    setCommandPool(pool).
    setLevel(vk::CommandBufferLevel::ePrimary);
auto cmd = device.allocateCommandBuffers(allocCI)[0];
cmd.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });

// barrier host write -> copyBuffer read
auto bufferMemoryBarrier = vk::BufferMemoryBarrier()
.setBuffer(stagingBuffer)
.setSize(vertexBufferSize)
.setSrcAccessMask(vk::AccessFlagBits::eMemoryWrite)
.setDstAccessMask(vk::AccessFlagBits::eTransferRead)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED);
cmd.pipelineBarrier(
    vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {},
    { }, { bufferMemoryBarrier }, { });

cmd.copyBuffer(stagingBuffer, vertexBuffer, { 0, 0, vertexBufferSize });

// copyBuffer write -> vertex read
bufferMemoryBarrier = vk::BufferMemoryBarrier()
.setBuffer(vertexBuffer)
.setSize(vertexBufferSize)
.setSrcAccessMask(vk::AccessFlagBits::eTransferWrite)
.setDstAccessMask(vk::AccessFlagBits::eVertexAttributeRead)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED);
cmd.pipelineBarrier(
    vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {},
    { }, { bufferMemoryBarrier }, { });

cmd.end();
auto submitInfo = vk::SubmitInfo().
    setCommandBufferCount(1).
    setPCommandBuffers(&cmdBuffer);
queue.submit({ submitInfo }, {});
queue.waitIdle();

```

# Answer
> 1 votes
It is fixed. The third argument to copybuffer was not being correctly initialized. The correct call should be like this:

```
cmd.copyBuffer(stagingBuffer, vertexBuffer, {{ 0, 0, vertexBufferSize }});

```

The line

```
cmd.copyBuffer(stagingBuffer, vertexBuffer, { 0, 0, vertexBufferSize });

```

actually creates three distinct copy regions.

---
Tags: vulkan
---


# Question
Title: Canvas UI elements out of place in Unity3d
I placed all elements in the places I want to show in the Game mode, nevertheless, when I go to Game Mode they are shown in the wrong place as it was shown in the pictures (they go to the center). I tried different modes of render mode but no one seems to work in this case. I want the elements to be fixed in the window no matter monitor size.

# Answer
It looks like you didn't configure your anchors correctly.

Here, I'd recommend creating a parent object for each cluster of controls on your screen, like the drop-down and grid of numeric widgets in your top-left corner. This will let you control the layout of objects within that cluster, independent of the location and size of that cluster on the screen.

Next, you'll want to set that cluster's anchors to the top-left of your canvas, by clicking on the anchor presets in the top-left of its RectTransform.

Also, place your pivot in the top-left corner of the shape, by setting Pivot.x = 0 and Pivot.y = 1.

Now, your PosX and PosY variables control the margin between this cluster of controls and the left / top sides of the display, and the width & height control the size of the parent (you can set up the controls inside to layout/scale within the bounds of the parent, if you like)

Try changing the shape of the game window inside the editor, to watch how the object repositions to stay tucked into the corner. Then, apply the same principles for items you want docked against top/right/bottom edges of the screen. By setting the anchor min/maxes to a fractional value, you can make the object stay glued to a point some percentage of the way along the screen.
> 1 votes

---
Tags: unity, gui
---


title: Text on touch in Algodoo

text:
# Question
Title: Text on touch in Algodoo
I have just started off in Algodoo and have only a basic knowledge of how it works.

I want to be able to create something that when it is touched by a ball with an English flag on, it shows England and when it is touched by a ball with an American flag, it says America.

How would I do this?

# Answer
> 0 votes
K so i fixed it. I didnt have the text size large enough for it to be seen so yea. Beginners mistake

---
Tags: game-design, scripting
---


title: Cursor issue in Unity

text:
# Question
Title: Cursor issue in Unity
Main question: How can I make this possible so that I can press a UI button inside the canvas while the cursor is locked?

Hello, I am creating a 3D video game. I have fully functional character control like walking using WASD keys and view rotation using mouse.

Now the last thing I need is to have cursor in the middle that can click on UI buttons on canvas like this:

https://www.youtube.com/watch?v=PPCwvqIqNxM&feature=youtu.be

I cannot click on UI buttons while the cursor is on locked constantly. So I created the pulse where the cursor will be locked and unlocked with a pulse so I can click on buttons.

This is the code I'm using:

```
//Inside the Update function.
float Lock = 0.0375f;
timer += Time.deltaTime;
if (timer > 0.02f && timer <= Lock)
{
    Cursor.lockState = CursorLockMode.Locked;
}
else if(timer > Lock)
{
    Cursor.lockState = CursorLockMode.None;
    if(timer >= Lock + 0.1f)
        timer = 0;
}
Cursor.visible = true;

```

It works, but not 100% proficient.

So, when I start building and run the game, here is what is happening:

https://www.youtube.com/watch?v=Fur6Al4zj3I&feature=youtu.be

What's happening is I cannot click the UI button after building and running the game. The only time I can press the button is when I am moving side by side while hovering over the button, otherwise if I stand still, I cant click the button.

This is the same crud I've been getting when I am designing one thing like a button for example, but when running, the button looks completely different from the designer. Same it applies here, I am running inside the Unity editor works, but when running inside the built game doesn't work like how it's suppose to.

For that, I just need help in what in the world I must do to make it work on both unity editor and built game, maybe I'm doing something wrong with the code? I need help. Any questions, please ask. Thank you.

# Answer
> 1 votes
Your code is fine, but logic is flawed. You cannot be sure that the cursor will be unlocked or locked at any given click, creating a possibility of unintended behaviour.

Instead, you can solve the problem using a global state machine:

```
UI Mode  <-A--  Game Mode
          --B->

```

During transition A: Unlock and show the cursor.

During transition B: Lock and hide the cursor.

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


# Question
Title: How to make a character that moves like a slinky?
I have a school assignment to make a 2D platformer game, with a character that moves like a slinky:

(Animated example from the assignment linked above)

1. At first, the character needs to grow in height over time
2. When the player presses a button, the character starts to bend toward the next platform
3. Its height when you press the button determines whether it will hit the next platform
4. After that it must shrink to its initial size, and it goes over again.

How can I approach this?

# Answer
Like @DMGregory said, there can be multiple ways of doing it. One way can be creating multiple blocks and connecting them to unity's physics joints. (Which you probably tried already)

Another way of doing it would be mesh deformation. You can create a spline bend to make a curve. See this tutorial on Spline Bending. It might help u get started.

From unity 2018, there is a new feature called Sprite Shape. It makes the sprite bending easy. There are not many tutorials available on Sprite Shape. But you can look into **Unity Documentation** to get some idea.

So, the idea should be

1. Scale the sprite on mouse down.
2. Then On mouse Up-

**(a)** Divide the sprite into equal bending points \[e.g. Say I wanna split it into 5 points, I will pick the points in each (sprite.bounds.y/5) position\]. You can insert point to the spline by ***spline.InsertPointAt(int index, vector3 point)*** method.

**(b)** Then Bend the sprite in each point. ***(spline.SetPosition(index, position))***. Here you will need some math calculations to pick where the next points should sit.

**(c)** When you have the new list of points you can now Lerp to the new points from the old one.

Let know in the comment if it helps, or you could make it work??
> 1 votes

# Answer
Since you didn't specify the language (maybe it was in the doc, but I can't read cyrillic, I'm sorry) I will give write some pseudocode / description.

First, you need the "slinky" object. I would build it out of two sub classes. "EndBlock" and "FillerBlock". Slinky only has one "EndBlock" to begin with, and is built like this:

```
buildWithPrecision(int precision){
    for (i){
        createNewFillerBlock()
        addBlockAsAChild()
    }

    createNewEndBlock()
    addBlockAsAChild()
}

```

At this point you should have a nice, hierarchical structure. This will be useful later.

Bending:

```
bend(float deltaTime, float bendingSpeed){
    getChildBlock().rotation.add(deltaTime * bendingSpeed);
    getChildBlock().bend();
}

```

This will work recursively. It should bend all the way until the last child.

At the endblock you should check if it touched the floor:

```
OnHit(Object other){
    if(other == floor){
        getTopParent().reverseBend();
    }
}

```

Reverse bend should stop bending, start bending the other way, and inform all the blocks that they have to shrink.

```
reverseBend(){
    getChild().bend(deltaTime, bendingSpeed);
    startShrinking();
}

```

I know this is not a fully working solution, but it should be a good way to start the project. If you have more questions, just add a comment.
> 0 votes

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


title: SDL2 doesn't render a window

text:
# Question
Title: SDL2 doesn't render a window
A tutorial's code from LazyFoo wonderful place's `01_hello_SDL` page doesn't show a white form, but a desktop's screen, like a screenshot. Something like:

The code:

```
//Using SDL and standard IO
#include <SDL2/SDL.h>
#include <stdio.h>

//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

int main( int argc, char* args[] )
{
    //The window we'll be rendering to
    SDL_Window* window = NULL;

    //The surface contained by the window
    SDL_Surface* screenSurface = NULL;

    //Initialize SDL
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
    }
    else
    {
        //Create window
        window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        if( window == NULL )
        {
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
        }
        else
        {
            //Get window surface
            screenSurface = SDL_GetWindowSurface( window );

            //Fill the surface white
            SDL_FillRect( screenSurface, NULL, SDL_MapRGB( screenSurface->format, 0xFF, 0xFF, 0xFF ) );

            //Update the surface
            SDL_UpdateWindowSurface( window );

            //Wait two seconds
            SDL_Delay( 2000 );
        }
    }

    //Destroy window
    SDL_DestroyWindow( window );

    //Quit SDL subsystems
    SDL_Quit();

    return 0;
}

```

Putting `PumpEvents();` or `while(SDL_PollEvent(&event))...` didn't work, unfortunately.

The machine's characteristics:

* CPU: i7 M620
* GPU: Intel Core Processor Integrated Graphics Controller
* GPU Driver: i915
* RAM: 8GB
* OS: KDE Neon 5.15.4 64bit, 4.15.0-47 Kernel, fully updated

# Answer
> 1 votes
By experimenting, we found that adding a short **delay**(~100ms) at the very start(after `SDL_CreateWindow`) fixes the issue. This might mean that there was a conflict between the `OS's Dekstop/Window Manager` and SDL when the latter renders too quickly. A short delay forces SDL to wait some time while `OS's Dekstop/Window Manager` handles the window's creation. This might also be something related to the compositor, which in our case - compiz.

In other words, the changes:

```
...
// Create window
window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
SDL_Delay(100); // A short delay should be put here(if doesn't work try increasing delay)

if(window == NULL)
{
...

```

With these changes, the white window opens successfully.

'Already wrote to the author of LazyFoo and hopefully they will alter the tutorial.

---
Tags: rendering, sdl2
---


# Question
Title: How to make party members appear and move to begin a conversation scene?
A common conversation starting trope in JRPGs, when the party is represented as a single character, is for the characters to come out of the player's position and begin talking with each other and the original character. Essentially they appear in the player's position and then move to a nearby square either one at a time or simultaneously. Then they start talking in classic JRPG fashion with one message box after another from one or another character.

What's the easiest way to do this in RPG Maker MV?

Is there a way to do it so the characters appear at the same time and move to their conversation positions simultaneously? Or is that not worth the trouble?

I can't find or create a tag for rpg-maker mv

# Answer
The way I do it is to have events for the party members (except the lead character, since they'll already be represented by the `player`). In the event that triggers your conversation, first do a "gather followers", then "change player followers" set to off, followed by setting a switch to make all the individual character events visible, and start moving them (it can be helpful to have a script that can set self flags on other events here, so you don't have your list of switches or variables cluttered up with a bunch of things that are only used for single conversations). If you can't predict where the player will be, then move the events while they're still invisible, then make them visible and start moving them to their final position. When the conversation ends, just reverse the steps.

The events that represent the party members should be set to an empty page by default, and should have a page with a condition for their actual appearance.

You have to do "gather followers" first, otherwise you don't know where the followers are when you need to put the events that represent them in place.
> 2 votes

---
Tags: scene, rpg-maker-mv
---