14 de set. de 2021

Getting screen size in World Coordinates

obj1.transform.position = Camera.main.ViewportToWorldPoint(new Vector2(1, 1)) + new Vector3(0, 0, 10);
obj2.transform.position = Camera.main.ViewportToWorldPoint(new Vector2(0, 0)) + new Vector3(0, 0, 10);

(1,1) is the top right corner of the screen in Viewport coordinates.
(0,0) is the bottom left corner of the screen in Viewport coordinates.

I add a Vector3 to adjust the Z position.

Camera.main.ViewportToWorldPoint() converts a viewport position into World postion.

If you move the Cam, the position of the corners (pink dots) follows the Cam, if inside Update().

8 de set. de 2021

(Kiduca) - Checkpoint (animation, SoundFX, FX, Code)


It opens when the player gets close and it becomes the actual "Checkpoint".

2 de set. de 2021

Teaching Unreal - Materials and Lights

  •  Base and Instance Materials
  • Color Material
    • Metallic
    • Roughness
    • Specular
  • Texture material with Normal (+ intensity)
  • Emissive materials  (+ intensity)
  • Directional Light
  • Point Light
  • Spot Light
  • Sky Light
  • Rect Light

19 de ago. de 2021

(Kiduca) Dr. Ignorancius new device: BigHammer

 In the Lab of Dr. Ignorancius, he experiments his new devices...

23 de mar. de 2021

Speed up Unity entering in play mode


How to get more free space in your C:\?

 I have an SSD as my System drive and it always gets full even with all my Softwares and Data been saved in another HD.

Searching on the web, I found this article that really helped me.

The Complete Guide to Creating Symbolic Links (aka Symlinks) on Windows

Basically, you must:

  • Copy the content of folder C:\Tmp into another partition, ex: D:\Tmp
  • Right-click D:\Tmp and select "Pick Link Source"
  • Go back to C:\, right-click and select Drop as "Junction"
C:\Tmp will be a "shortcut" to D:\Tmp.
The content will be at D:\Tmp, but if you write in the Console window C:\Tmp, you will see all the files.

3 de out. de 2020

Moving like "Castle Crashers"

 A simple example of moving your character like the game Castle Crashers.

  • Up and down limits
  • Move Up and Down inside a Y range
  • Move Right and Left
  • Jumping
    • Go up while jumping
    • Go down while jumping

Download Code Example

29 de jun. de 2020

Pink materials when testing Addressables in Editor

If your project is set for Android and you set the addressable for "Use existing builds" (will load remotely the bundles) some materials will turn pink when you run in editor mode because the editor uses Direct3D11 as API.
You must change the settings to use OpenGLS3 in the editor to correct this.

30 de abr. de 2020

ITweenFRC - Easy UI animation

I´ve created a Class that works with iTween and turns it easier to Move and Scale UI Elements.

  1. Download the iTween package at Asset Store.
  2. Drop the iTweenFRC Class into a GameObject and set its parameters:

  • Target -position or scale to reach
  • Delay - time to wait to start the tween
  • Time - time that will last the tween
  • Mode - Move or Scale
  • Ease Type - A list of Easetype.(Ex: linear, spring, etc..)

Download Here: ITweenFRC

27 de fev. de 2020

OBS -Black Screen recording

When I try to record from my Notebook, the screen is always black, no matter what I configure de app.
I found the solution in this Page.
Basically,I opened the Windows Settings - Graphic setting and set "Power Saving" for the OBS executable.

14 de jan. de 2020

Jumping like Mario

We can control:
  • The Highest Jump Height (JumpVelocity and Gravity)
  • The velocity he goes Up (JumpVelocity and Gravity)
  • The velocity he goes Down (Fall Multiplier)
  • The Lowest Jump Height (Low Jump Multiplier)

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

public class Jump : MonoBehaviour
    Rigidbody2D rb;

    public float speed = 5;                 // Horizontal speed to move

    public float gravity = -5;              // force that influences when jumping (going up with button, going up without button, falling)
                                            // this force stops the jump for going up.
    public float jumpVelocity;              // velocity set for the jump
    public float fallMultiplier = 2.5f;     // force that inflences when the player is falling
    public float lowJumpMultiplier = 2f;    // force that influences when the player is going up withot pressing the button

    float hor;

    public LayerMask whatIsGround;          // what is floor?
    public Transform feetPos;               // where the isGrouded OverlapCircle is positioned
    public float checkRadius;               // the radious of OverlapCircle
    bool isGrounded;                        // if its grounded or not

    private void Start()
        rb = GetComponent<Rigidbody2D>();

    private void Update()
        hor = Input.GetAxis("Horizontal");

        isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);

        if (Input.GetButtonDown("Jump") && isGrounded)
            GetComponent<Rigidbody2D>().velocity = Vector2.up * jumpVelocity;

    private void FixedUpdate()
        rb.velocity = new Vector2(hor * speed, rb.velocity.y);

        if (rb.velocity.y < 0) // if is falling, accelerate
            rb.velocity += Vector2.up * (-fallMultiplier);
        else if (rb.velocity.y > 0 && !Input.GetButton("Jump")) // if is going up and not pressing button, force down
            rb.velocity += Vector2.up * (-lowJumpMultiplier);

        // always applied if not grounded
        if (!isGrounded)
            rb.velocity += Vector2.up * (gravity);

    private void OnDrawGizmos()
        bool isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);

        if (isGrounded)
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(feetPos.position, checkRadius);
            Gizmos.color = Color.green;
            Gizmos.DrawWireSphere(feetPos.position, checkRadius);

13 de jan. de 2020

Yes! I bought one Atari 2600 "Darth Vader"

This vacation I finally bought the first video game that my father gave me when I was 8 years old: Atari 2600 "Darth Vader"!
It was broke, but I found a guy that helped me fix it.

In the same weekend, I bought some cartridges at the fleamarket
  • Space Invaders
  • Pitfall
  • Frogger
  • Nexar
  • Fantastic Voyager
  • Damas
The Frogger cartridge broke the day after I had bought it, then I have to fix it. But now, everything is working just perfect! :)

3 de jan. de 2020


I was looking for an easy way to move GameObjects around, and I found the iTween Asset.
  1. Import the Asset
  2. Insert the code in Class from the GameObject that you want to move.

Hashtable ht = new Hashtable();
ht.Add("x", transform.position.x);
ht.Add("y", transform.position.y + 1f);
ht.Add("time", 2);
ht.Add("oncomplete", "AnimationEnd");
ht.Add("oncompleteparams", sender);
ht.Add("easetype", iTween.EaseType.linear);
ht.Add("scale", new Vector3(1, 1, 1));
iTween.ScaleTo(panel, ht);
iTween.MoveTo(gameObject, ht); 


One problem happened using iTween inside a GameObject that animate another GameObject. The "oncomplete" was never called. I found the solution in this Post.

29 de dez. de 2019

Change Animator Controller Asset in Runtime

I needed to change the Animator controller in runtime and one solution was to load de Animator Asset from Resources folder.

  • Put the Assets in Resources folder
  • Load de asset using:

animator.runtimeAnimatorController = Resources.RuntimeAnimatorController("AssetControllerName");

3 de dez. de 2019

Visual Studio 2019 Community without intellisense for Unity

Edit > Preferences > External Tools > External Script Editor

Find your VS 2019, normally it´s installed in 

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe

27 de jun. de 2019

Another way to create Fade by Code

This must be inside a Coroutine method that returns a IEnumerator.
TransitionTime is the time that you want it takes to perform the Fade.

20 de jun. de 2019

Dropbox - aproveitar pasta já existente

Cheguei um dia e meu Drobox estava padindo para se logar. Fiz o login e percebi que ele estava atualizando TODO o conteúdo novamete na pasta padrão. Eu uso o conteúdo do Dropbox em um HD externo.

  1. Desvinculei a minha conta do dropbox no computador.
    botão direitono icone - configurações - preferências
    Conta - desvincular este dropbox...
  2. Fiz login novamente
  3. Opção de escolher pasta destino

16 de jun. de 2019

How to create a documentation of your Project

  1. Install Doxygen 
  2. Open the DoxygenWizard
  3. Step 1: find the folder where the Doxygen was installed.
  4. Step 2: fill the basic information:
    Project name
    Source code directory (folder where you can find your scripts)
    Destination directory (where the doc will be saved)
  5. Click next until the RUN tab.
  6. "Run doxygen"
Is that simple! Now you just need to click on "Show HTML output"

How to create a C# Snippet in Visual Studio Community

  1. Create a new XML File
  2. Copy de template bellow.
  3. Change de Title, Author, Descsription, Shortcut and mainly the CDATA content.
  4. Save as FileName.snippet
  5. Open
    Tool - Snippet Manager and import the XML file into CSharp "My Code Snippets"
  6. Done

Now, you just need to write the Shortcut and press TAB.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
            <Code Language="">

17 de fev. de 2019

ShaderGraph - Vertex displacement Shader

Testing Vertex displacement Shader using ShaderGraph.
A sphere modifying its vertices.

Download Shader

1 de ago. de 2018

ShaderGraph - Refraction

In LW Render Pipeline you have a property called "Opaque Texture". If you check it, you can use a Texture 2D Node with the reference named "_CameraOpaqueTexture" to access the camera content and than you can do whatever you want with it :)

24 de jun. de 2018

Android - Debug your game (Unity)

There is no way, you´ll need to debug your game/app directly in your Android device.
So, for that, you need to:

  1. Set up Unity to Build in Developer mode
    1. File - Build Settings - Development Build
      1. Run Device - choose the device that is connected via USB, my example Lenovo A7010
      2. Script Debugging
    2. Build and Run
    3. Console - Choose "Android Player (XXXX)"
  2. Wait until your game starts into your device
  3. Set up Visual Studio 2017
    1. Debug - Attach Unity Debugger
      1. Your devices must be showed in the list, choose it.
  4. Now,  you just need to put breakpoints to stop the game and debug what you want.
Problem: The build freezes at the last part of the process: copying apk package when using "Build and Run". The solution is:
  • Changed the USB port (front to back por of the PC)
  • or Delete the app in the cellphone
I used "c:\adb>adb install -r Minigames.apk" to try to send the apk by command line, but it was not going.

21 de jun. de 2018

Looping a range of number using mod "%"

If you want to loop through a range of number and starts from the beginning again, you can use Mod "%".

destPoint = 0;
destPoint = (destPoint + 1) % patrolTargets.Length;

if patrolTargets.Length = 5, for example, destPoint will be 0, 1, 2, 3, 4 and 0 again, if the expression is inside a loop statement.

20 de jun. de 2018

Limit Max Width of a Layout Component in Unity

Problem: Expand the size of a button according to its text, but with a limit in the width.

After a while searching for something to solve my problem, I found this link that helped me.

2 de jun. de 2018

Parabole movement

How to make a GameObject jump as a Parabole.

public float height;
    public float duration;

    void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
            StartCoroutine(Jump(height, duration));

    IEnumerator Jump(float height, float duration)
        float lastY = transform.position.y;
        Vector3 startPos = transform.position;
        Vector3 endPos = transform.position;
        float time = 0f;

        while(time <= 1)
            time += Time.deltaTime / duration;
            float yOffset = height * (time - (time * time));
            transform.position = Vector3.Lerp(startPos, endPos, time) + yOffset * Vector3.up;

            yield return null;

        transform.position = new Vector3(transform.position.x, lastY, transform.position.z);

1 de jun. de 2018

Unity: resize a Button with its content (text)

If you want that your Canvas Button to resize according to its content.
A good way to solve this problem.

How to Git with Unity

I found this interesting article on How to Git with Unity.


22 de mai. de 2018

Serialize and Deserialize Json and Json Array in Unity

If you need a more complex serialization, the native JsonUtility will not help you.

In this post you can find the solution for the problem.

20 de mai. de 2018

Create a Normal Map in 3DS max

  1. Create a Plane Standart Primitive: plane1
  2. Select the plane1 and Unwrap it

  3. Duplicate the Plane and make some modifications: plane2

  4. Put plane1 in the same position of plane2

  5. With plane1 selected,open Rendering->Render to Texture
    1. click on Pick to select the Plane that we will create the normal: plane2
    2. clck on Options

    3. In Options window, choose in Orientation Green: Up (to use in Unity)
    4. Click on Setup

    5. In Setup window, in Render tab, check Enable Global Supersampler

    6. Close setup window, Projection Options
    7. Back to Render to Texture window, choose Use Existing Channel
    8. Add texture element NormalsMap
    9. Choose "Bump" in Target Map Slot
    10. Choose the map resolution (1024x1024)

    11. plane1 now has an Projection Modifier

    12. Selecting Projection Modifier, we can see the Cage section, click in Reset and increase the Amount until the "cage" is surrounding the modification of plane2

    13. Render To Texture: click in Render

12 de abr. de 2018

Unity Animator states not showing which is playing at runtime.

If your Animator window is not showing a little progress bar when you hit play, try to select the GameObjet that has the animator controller that references to this Animator asset.

25 de mar. de 2018

PHP - enable cross-origin resource sharing

If you don't have access to configure Apache, you can still send the header from a PHP script. It's a case of adding the following to your PHP scripts:
Note: as with all uses of the PHP header function, this must be before any output has been sent from the server.
Site: https://enable-cors.org/server_php.html

20 de mar. de 2018

3D max - How to remove Peel seams (blue seams)?

In the Unwrap UVW panel > Click Edit Seams to turn on Edit mode > Alt+Left Click the seam you want to remove.

23 de fev. de 2018

How to delete the Unity´s GI cache?

"The GI cache is used by the Global Illumination (GI) system to store intermediate files when precomputing real-time GI, and when baking Static Lightmaps, Light Probes and Reflection Probes. The cache is shared between all Unity projects on the computer, so projects with the same content and same version of the lighting system (Enlighten) can share the files and speed up subsequent builds."

Find the settings for the GI cache in Edit > Preferences > GI Cache on Windows, or Unity > Preferences > GI Cache on macOS.

source: https://docs.unity3d.com/Manual/GICache.html

Where does Unity keep the dowloaded Packages from Asset Store?

You can find the downloaded Packages from Assets Store in the folder:

C:\Users\YOURU_SER\AppData\Roaming\Unity\Asset Store-5.x

13 de jan. de 2018

Unity - Problem building for Android

When I was trying to build for Android, Unity started to show me an error message:

"Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details."

I found this post that solved the problem.

8 de jan. de 2018

Controle PS4 no PC via Bluetooth

Achei este artigo do Tecmundo.
Fiz os passos "Dualshock com cabo" e depois "Dualshok 4 com Bluetooth".

Rodando perfeito!

  • Ligue o Bluetuth no Note/PC
  • Abra o Painel de Controle
  • Pressione PS + Share no Controle do PS4
  • Clique em avançar

21 de dez. de 2017

Vector3.SmoothDamp - smooth transaction between 2 vectors

Vector3 velocity;
public float time = .5f;

transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref velocity, time);

Using Bounds Class to get center of many objects

We can use the Bounds Class to get the center of many objects in the scene.

 private Vector3 GetCenter()
  if (targets.Count == 1)
   return targets[0].position;

  Bounds bound = new Bounds(transform.position, Vector3.zero);
  foreach (Transform target in targets)

  return bound.center;

13 de dez. de 2017

Texture Tools for Adobe Photoshop - NVidia Plugin

Plug in for Photoshop to create Normal Map from an image. See thisTutorial

11 de out. de 2017

C# - instantiating a Class from String

How can we instantiate a class from a String?

string state = "BeginState";

Type type = Type.GetType("Assets.States." + state); object instance = Activator.CreateInstance(type, new object[] { stateManager }); stateManager.SwitchState((IStateBase)instance);

5 de out. de 2017

Working with Relative Paths in 3ds Max

3D Max Menu - Manage - Asset Tracking
Select All files
Right Click - Make Path Relative to Project folder


Customize - preferences - Files - Conver Local file paths to Relative

7 de jul. de 2017

Testing your game with "Unity Remote"

To test the games that we are developing into a real cell phone, Unity provides us with the app "Unity Remote".
But it is not so easy as plug the cell in the computer and press Play in Unity Editor.

I had some troubles connecting my Lenovo Vibe K6 - Android 6.0.

After I unlocked the "Developer option" in my cell phone:
  • Settings 
  • About device 
  • Click many times over "Build Number"
The "adb devices" prompt command was not showing my Lenovo :(, so, it was not being detected as a device to be used by another application, even if in the Explore it was been shown.

Inside "Settings - Developer", I had to setup the configuration´s USB protocol to "PTP (Picture Transfer Protocol)"

Then when I run adb, it shows me my device and Unity started to play the game direct in Unity Remote.

If adb is showing the device, you just need to run the "Unity Remote" in your cell phone (download in Google play/Apple Store) and run your game in Unity. It will automatically run the game on your device.

It´s MUCH better than transfer the .apk file every time that you need to test a new functionality.

Problem using ASUS Zenfone with Unity 2019.1

  1. Android - enabled Developer Options
  2. Developer Options
    1. Keep Awake
    2. USB debug
    3. Select USB Options
      1. Load this device

  1. Unity
  2. Project Settings - Unity Remote - Device - Any Android Device
  3. Build Settings - Run Device -
  4. **Preferences - External Tools
    1. Uncheck Andoird SDK Tools Installed with Unity
    2. Fill the path with the SDK path:
It does not matter the order that I open Unity, connect android or open Unity Remote

6 de jul. de 2017

Background Paralax - model 1

There are some ways to make the Background run as if the camera was moving.

In this example, we move the Gameobject with the SpriteRender with a child with another Gameobject with the same image (duplicate de Gameobject) in the scene and when it reachs the startPosition + hisSize, it comes back to the startPosition.

using UnityEngine;

public class Paralax : MonoBehaviour {

    public float scrollSpeed;
    public float tileSizeZ = 0;     // if changed in edit time, it uses this value for the size of the SPriteRenderer
                                    // Used in images that are shorter than the screen width

    private SpriteRenderer sprite;  // the SpriteRender of the GameObject
    private Vector3 startPosition;  // Start position of the GameObject

    void Start () {
        sprite = GetComponent<SpriteRenderer>();
        startPosition = transform.position;

        if (tileSizeZ == 0)
            tileSizeZ = sprite.bounds.size.x;

    void Update () {
        /* Repeat works like:
         if Time.time * scrollSpeed < tileSizeZ, newPosition = Time.time * scrollSpeed
         else, newPosition = (Time.time * scrollSpeed) - (loopIndex * tileSizeZ) */
        float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeZ);
        transform.position = startPosition + Vector3.left * newPosition;

2 de jul. de 2017

Following Mouse in 3D

A simple example of an object following the mouse in 3D environment.

using UnityEngine;

public class FollowMouse : MonoBehaviour

    public float force;

    Rigidbody ballRigid;
    Ray ray;

    void Start()
        ballRigid = transform.GetComponent<Rigidbody>();

    private void Update()
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin, ray.direction * 100, Color.cyan);

    void FixedUpdate()
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100))
            if (hit.collider.tag == "Terrain")
                Vector3 direction = hit.point - transform.position;
                ballRigid.AddForce(direction * force);

1 de jun. de 2017

LookAt2D(Vector 3)

A method to rotate a Gameobject towards a Vector3 position.
In the example bellow, the Tank´s Canon is following the Mouse.

Put this code in the object that you want to rotate. Call the method inside the Update().

void LookAt2D(Vector3 target) // target is the Vector to look at
        // Get point B based on point A as 0,0,0
        Vector3 targetDir = target - transform.position;

        // Use Tangent to get the Angle. 
        // Tan(x) = catetoOposto/catetoAdjacente
        float angleRad = Mathf.Atan2(targetDir.y, targetDir.x);
        // convert angle to Degrees
        float angleDeg = angleRad * Mathf.Rad2Deg;

        // I´ll rotate "angleDeg" in "Vector3.forward" Axis
        transform.rotation = Quaternion.AngleAxis(angleDeg, Vector3.forward);

31 de mai. de 2017

Fade Out and Fade IN using Mathf.Lerp()

Lerp is a very interesting function because it changes a value between A and B depending on C.

Math.Lerp(A, B, C);

If C varies from the beginning to the end, you can simulate an Fade In or Fade out transition, for example.

In the example below, I want to go from 1 (A) to 0 (B) (fade out transition) in 3 seconds.

The for loop will take 3 seconds to complete (Time.deltatime / 3) and C will be an incremental value from 0 to 1.

We can think as if it was an Slider controller: when C are at the left (0), the value is A, if you slide to the right (1) the value is Y.

SpriteRenderer sprite = GetComponent<SpriteRenderer>();
void Start()

    IEnumerator fade1()
        Color newColor;

        for (float x = 0f; x < 1f; x += Time.deltaTime / 3)
            newColor = new Color(1, 1, 1, Mathf.Lerp(1, 0, x));
            sprite.color = newColor;

            yield return null;


26 de mai. de 2017


An example of how to use Raycast to show the path where the Gameobject will pass.
A tip is, you must disable Edit > ProjectSettings > Physics2D > Queries Start in Collider
This mean that the Raycast will not collide with the Collider where it starts in.

public int numPositions = 3;
public Vector3 diretion = new Vector2(1, 1);
public LineRenderer lineRenderer;
void UpdateLineRenderer()
    Vector3 actualDirection = diretion;
    Vector3 actualPosition = transform.position;
    Vector3 lastPosition = actualPosition;

    lineRenderer.SetPosition(0, actualPosition);

    for (int x = 1; x < numPositions; x++)
        RaycastHit2D hit = Physics2D.Raycast(lastPosition, actualDirection);
        lineRenderer.SetPosition(x, hit.point);
        lastPosition = hit.point;

        actualDirection = Vector3.Reflect(actualDirection, hit.normal);

We can use the Debug.DrawRay to see the Raytrace:

Debug.DrawRay(transform.position, diretion*100);

Drawing line in Runtime

void DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f)
        GameObject myLine = new GameObject();
        myLine.transform.position = start;
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.endColor = color;
        lr.startWidth = 0.02f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, end);
        //GameObject.Destroy(myLine, duration);

Converting Angle to Vector direction

If the reflected angle (green) is greater than 50º, I want to change its direction for an angle of 45º (orange).

public Vector2 direction = new Vector2(1,1);

void FixedUpdate () {
 rb.velocity = direction * velocity;

private void OnCollisionEnter2D(Collision2D collision)
 Vector2 normal = collision.contacts[0].normal;
 float angle = Vector2.Angle(direction, normal));
 float angleComp = 180 - angle;
 Vector2 newDirection =  Vector2.Reflect(direction, normal);
 if (angleComp > 50)
  newDirection = Quaternion.AngleAxis(direction.x * 45, Vector3.forward) * normal;
 direction = newDirection;

Changing the Sprites of a Character in Runtime

Do you have two or more characters in your game with the same structure, animation but you need to change its Sprites to make them look different?

Do you want to change the Sprite of a character in order to change its look, for example, just to change its clothes or objects that it's carrying?

Put this Component into your Character´s GameObject.
In the Inspector, change the spriteSheetName property to the name of your SpriteSheet Asset.
The Spritesheets must have the same "sliced" sprites name, for example: head, body, etc.

using UnityEngine;
using System;

 * This script changes the sprite of a gameobject in runtime
 * the sprites must be in the Resources folder
 * */
public class ChangeSprite : MonoBehaviour {

 public String spriteSheetName; // name of sprite to be loaded

 void LateUpdate () {
  var subSprites = Resources.LoadAll<Sprite>(spriteSheetName);
  foreach(var renderer in GetComponentsInChildren<SpriteRenderer>()) // get all SPriteRenderer from my GameObject
   string spriteName = renderer.sprite.name;
   var newSprite = Array.Find(subSprites, item => item.name == spriteName);

   if (newSprite)
    renderer.sprite = newSprite;


23 de mai. de 2017

How to limit the moviment of a GameObject into the Screen

This function limits the moviment of a GameObject to it´s Cam Screen.

private void CheckLimits(Vector3 posAtual)
    SpriteRenderer renderer = GetComponent<SpriteRenderer>();

    float newX = Mathf.Clamp(transform.position.x, 
        cam.ScreenToWorldPoint(new Vector3(0, 0, 0)).x + renderer.bounds.size.x/2, 
        cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, 0)).x - renderer.bounds.size.x / 2);

    transform.position = new Vector3(newX, posAtual.y, posAtual.z);

19 de mai. de 2017

Anima2D Spring Bones BUG

If you animate a character with Anima2D and uses Spring Bones to apply physics on some bones, you will realize that if you flip your character, an odd bug happens.

The bones with "spring bones" applied to them, become strange and start to behave in a manner that we don´t want to.

To solve that, you must check "Is Animated" in the Spring Bone Component :)

2 de mai. de 2017

How to set the "New Line" convention in Visual Studio

Each OS has theis own way to deal with New Line character.
Win = CT LF
Mac = CR
Unix = LF

In VS 2015 you go to:

  1. File
  2. Advance save options
  3. Choose the correct option for your OS
In VS 2017 you go to:
  1. File
  2. Save As
  3. Click the down arrow on the Save button and clicking "Save With Encoding...".
  4. Choose the correct option for your OS
You can also add it back to the File menu through Tools->Customize->Commands if you want to.

1 de mai. de 2017

How to know if I collided with a especific side of a GameObject

Sometimes we need to detect if a Gameobject collided with a especific side of another GameObject, or even a side of the Screen.

We can do that cheking the "Normal" of the collision´s angle.

if (collision.collider.name == "Wall") { // collided with screen top
    Vector2 normal = collision.contacts[0].normal;
    if (normal == Vector2.down)
this.enabled = false;

How to "Reflect" the angle of a collision

How to get the Screen (Camera) Size


GameObject following Mouse

Vector3 temp = Input.mousePosition;
temp.z = 10;
transform.position = new Vector3(Camera.main.ScreenToWorldPoint(temp).x, transform.position.y, transform.position.z);

How to get the size (Wrold size) of a GameObject in 2D

SpriteRenderer renderer = GetComponent ();

Ways to move an object in 2D

I found some ways to move an GameObject in the 2D enviroment.

  1. First, I get the Input from the Keyboard or the Mouse:

    float direction = Input.GetAxis("Horizontal");
    float direction = Input.GetAxis("Mouse X");

    Both returns values between -1 and 1, depending on the direction.
  2. I get the actual position of the object

    Vector3 posAtual = transform.position;
  3. Move it!

    # Changing the X of the vetor
    transform.position = new Vector3(posAtual.x + (velocity * mouseDir * Time.deltaTime), posAtual.y, posAtual.z);

    # Adding a new vetor to the actual position vector
    transform.position += new Vector3(velocity * direction * Time.deltaTime, 0, 0);

    # Adding a vector by direction
    transform.position += transform.right * velocity * direction * Time.deltaTime;

    # Following the mouse
    Vector3 temp = Input.mousePosition;
    temp.z = 10;
    transform.position = new Vector3(Camera.main.ScreenToWorldPoint(temp).x, posAtual.y, posAtual.z);

    # Adding Force
    rb.AddForce(transform.right * force * direction);

    # Using the Tranform method "Transalte"

    transform.Translate(velocity * direction * Time.deltaTime, 0, 0);

15 de mar. de 2017

ADB não reconhece dispositivo

De vez em quando, ao rodar o ionic run android, não aparece device para ele rodar mesmo o celular estando conectado via USB.

\adb devices
retorna vazio

Eu instalei 2 pacotes de drivers que achei na web
INSTALL G:\Download\Driver\Android-adb-driver.exe (NÃO SEI SE É NECESSÁRIO)
INSTALL G:\Download\Driver\MotorolaDeviceManager_2.5.4.exe (NÃO SEI SE É NECESSÁRIO)

** um deles apaga o PATH de variáveis do sistema, tem que reinstalar:

                          Procurar driver no Computador - permitir que escolha de uma lista - adb
                                      Android Sooner ADB Testing Interface

In Android, "Developer Options", I enabled "Debug USB"

17 de fev. de 2017

PHP connecting with MySQL

There are 3 ways to connect PHP with MySQL:

  1. PHP's MySQL Extension (old one)
  2. PHP's mysqli Extension (current using)
  3. PHP Data Objects (PDO)
I´ll talk about the second one: mysqli.

mysqli means "MySQL improved extension".

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
  • Object-oriented interface
  • Support for Prepared Statements
  • Support for Multiple Statements
  • Support for Transactions
  • Enhanced debugging capabilities
  • Embedded server support
As well as the object-oriented interface the extension also provides a procedural interface.

Procedural interface
 $mysqli = mysqli_connect("example.com", "user", "password", "database");  
 if (mysqli_connect_errno($mysqli)) {  
   echo "Failed to connect to MySQL: " . mysqli_connect_error();  
 $res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");  
 $row = mysqli_fetch_assoc($res);  
 echo $row['_msg'];

Object-oriented interface
 $mysqli = new mysqli("example.com", "user", "password", "database");  
 if ($mysqli->connect_errno) {  
   echo "Failed to connect to MySQL: " . $mysqli->connect_error;  
 $res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");  
 $row = $res->fetch_assoc();  
 echo $row['_msg'];  


7 de jan. de 2017

Apagar arquivo com nome muito extenso

Assuming you are on windows:

What I always do is use subst to create a driveletter asccociation with part of the path.

Then go to the new driveletter and navigate to the files that have long names. You should now be able to rename/delete/etc them. The reason this works is because the path itself is no longer containing >255 chars.
To create a subst folder
Start a commandprompt (no admin privileges needed)
Use cd to navigate to the folder you want to go (you can use tab to autocomplete names
type subst j: . to create the driveletter association. (instead of the . you can also type the entire path)
Now in explorer you have a new letter. Go to it and do whatever you need to do to the .cache files.
Go back to your cmd window and type subst /d j: to remove the drive or alternatively, restart your pc.

EDIT: A trick I learned which can shorten this quite a bit. From the explorer window where you have trouble, click the addressbar so you can type in it, then type cmd and press Enter to start a command prompt at that location, then proceed at step 3. :)

EDIT2: Okay, this trick can be expanded even further. If you are in explorer at the right path, just type in subst j: . in the addressbar and press enter. A command window will pop up, execute the command and close again, and there you go, a new drive pops up in explorer.

fonte: http://superuser.com/questions/755298/how-to-delete-a-file-with-a-path-too-long-to-be-deleted

26 de dez. de 2016

Using Cordova Plugin without ngCordova

I needed to verify the Wifi that the app is connected and I didn´t find the Cordova plugin in ngCordova list, so I found the WifiWizard plugin that had all that I needed and used it inside the app.
Below, I put the steps that I did to get it working:

  1. ionic start WifiWizard blank
  2. cd WifiWizard
  3. ionic platform add android
  4. cordova plugin add WifiWizard
  5. ionic run android -l
One tip is to put the method call of the plugin iside a $ionicPlatform.ready(function() { }

.service('WifiService', function($ionicPlatform) { 
  var service = this; 
  $ionicPlatform.ready(function() { 
    WifiWizard.listNetworks(successNetwork, failNetwork); 

   var successNetwork = function(response) { console.log("successNetwork"); } 
   var failNetwork = functionresponse { console.log("failNetwork"); } 

We can also call the plugin using:

3 de out. de 2016

Sorocaba - vereadores 2017

Em vermelho quem foi reeleito:

3 de ago. de 2016

Matéria na TV Tem Sorocaba com Kiduca


2 de ago. de 2016

Ionic - Device communication time out

If I let the file "platforms\android\cordova\node_modules\q\q.js" without changes, when I try to build the apk or test direct in the phone, it gives me an error:

Error: Device communication timed out. Try unplugging & replugging the device.

To solve the problem I must change the code from

var timeoutId = setTimeout(function () {
deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
}, ms);


var timeoutId = setTimeout(function () {
deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
}, 10000000);

I found the solution in this post.

Ionic - stopped building for Android

I finished the day building the app for Android normally. The next day, when I tried to build, it gave me an error message:

ionic Execution failed for task ':merge Debug Assets'

The solution was to remove the Android platform from the project and add it again.

> ionic platform remove android
> ionic platform add android

6 de dez. de 2015


Com a atual situação econômica do pais, mais as frequentes descobertas de corrupção, eu comecei a refletir sobre a influência da população nisso tudo e principalmente a minha participação, e cheguei a conclusão que os "políticos" do executivo, legislativo e judiciário são exatamente a representação da nossa cultura política, ou seja, é o reflexo de nossa total ignorância no assunto.

Sei que não posso generalizar, mas acredito que a grande maioria da população se enquadra como "analfabetos políticos". Não sabemos nada sobre o assunto e queremos reclamar.

Por conta disto, decidi estudar e tentar influenciar o meio que participo (família, amigos, trabalho, etc) para nos politizarmos com o intuito de nos tornarmos melhores eleitores e fiscalizadores.

Temos que conhecer o processo, como funciona o básico para podermos colocar pessoas competentes na posição de representantes do povo e depois numa segunda etapa, poder cobrar dessas pessoas a sua função.

Algumas perguntas que fiz para mim mesmo e fiquei assustado com o resultado:

  1. Quantos vereadores trabalham na Câmara de vereadores da sua cidade?
  2. Fale o nome de 5 vereadores ativos.
  3. Quem foi o último vereador que você votou?
  4. Quantos deputados estaduais trabalham na Assembléia Legislativa?
  5. Fale o nome de 5 deputados ativos.
  6. Quem foi o último deputado estadual que você votou?
  7. Quantos deputados federais trabalham da Câmara dos deputados?
  8. Fale o nome de 5 deputados federais.
  9. Quem foi o último deputado federal que você votou?
  10. Quantos senadores trabalham no Senado Federal?
  11. Quantos senadores representam o estado de SP?
  12. Quem são eles?
  13. Você sabe quanto cada um deles ganham por mês e quais seus benefícios? Vereadores, deputados e senadores?
  14. Você pesquisou se havia ocorrências na Justiça e no Tribunal de contas dos seus candidatos antes de votar? Se ele já tem um passado criminoso na política, por que colocá-lo novamente?

Isso seria o básico de conhecimento, o nível intermediário seria o acompanhamento de quem você votou (ou algum legislador adotado).

Pois é meu amigo, se você foi bem no questionário acima, parabéns!
Na minha opinião, você tem o direito de reclamar da situação atual do Brasil. Agora, se você (assim como eu) não sabe muitas respostas, acho melhor estudar primeiro.

"O Analfabeto Político

O pior analfabeto é o analfabeto político. Ele não ouve, não fala, nem participa dos acontecimentos políticos. Ele não sabe que o custo de vida, o preço do feijão, do peixe, da farinha, do aluguel, do sapato e do remédio dependem das decisões políticas.

O analfabeto político é tão burro que se orgulha e estufa o peito dizendo que odeia a política. Não sabe o imbecil que, da sua ignorância política, nasce a prostituta, o menor abandonado, e o pior de todos os bandidos, que é o político vigarista, pilantra, corrupto e lacaio das empresas nacionais e multinacionais."

Bertolt Brecht: O Analfabeto Político O pior analfabeto...

Eu era analfabeto político, e me alfabetizei!
Quero que o Brasil mude, por isso mudei!
E você?

Respostas das perguntas:

  1. 20 vereadores em Sorocaba
  2. Depende da cidade
  3. Resposta pessoal.
  4. Em SP 94 deputados
  5. Lista de deputados estaduais (SP)
  6. Resposta pessoal.
  7. 513 deputados federais
  8. Lista dos deputados federais
  9. Resposta pessoal.
  10. 81 senadores
  11. 3 senadores
  12. Lista dos senadores que representam SP
  13. Quanto ganha?
  14. Exemplo de senador com ocorrências