Uncategorized

【Reverse Engineering a game】- w/ Godot64

Posted on Updated on

I’m lazy following tutorials and when I was told Godot64 has a Game Jam with an abundance of source code projects uploaded on Github I decided to start figuring out how these games by diving straight into the code.

NOTE: It helps to have a good understanding of Python to understand GDScript. If you don’t then try to follow along because it’s just english anyway. Ok here we go lets start coding.

I chose MouseBoat ( https://github.com/CowThing/MouseBoat )
Official site: https://cowthing.itch.io/mouse-boat

Finding input controls:
Lets not waste any time.

First step, understanding that every application starts with Main.gd. So I grab the code here → https://github.com/CowThing/MouseBoat/blob/master/scripts/main.gd

Line 16 is our default function. Not a constructor, just where initialization begins.

func _ready():
	randomize()
	set_process_input(true)

	AudioServer.set_stream_global_volume_scale(0.5)
	load_fish()

	get_node("Main Menu").popup()
	get_node("Main Menu Camera").make_current()

Every input control is initialized with set_process_input(true).

Scrolling further down are a bunch of functions used for initialization and loading models, sound files, UI stuff etc.

Now I reach line 27:

func game_start():
	player.set_state(player.STATE_MOVE)
	player.get_node("Camera Pivot/Camera").make_current()

Ok this looks relevant. I don’t know what player is so I do a quick search in the same script and i return to the top of the file to find this at line 13:

onready var player = get_node("Objects/Player")

get_node(…) looks through your hierarchy in the Godot editor shown below

スクリーンショット 2016-06-11 23.03.43

Under our the Objects node is a child node Player. Hitting F key in the 3D scene in our editor focuses into our player character.

スクリーンショット 2016-06-11 23.05.09

Perfect. Now, we know how the player character is loaded but how do we find out which script it’s using?

Look in your inspector on the right of the editor to find under Script:

スクリーンショット 2016-06-11 22.48.33

We know now that Boat.gd is the script it uses for controls. Opening this file and we see that a constant was defined at line 10 for our get_node previously:

const STATE_MOVE = 0

Searching further into our code on where STATE_MOVE is defined we reach line 79:

	if current_state == STATE_MOVE:

		if moveF:
			var d = get_transform().basis.z
			lv += d * movespeed * step

		elif moveB:
			if lvlen <= movespeed * 0.2:
				var d = -get_transform().basis.z
				lv += d * movespeed * 0.2 * step

				if lvlen >= movespeed * 0.2:
					lv = lv.normalized() * movespeed * 0.2

		if moveL:
			av.y += step

		if moveR:
			av.y -= step

		av.y = clamp(av.y, -turnspeed, turnspeed)

		if lvlen >= movespeed:
				lv = lv.normalized() * movespeed

		if lvlen > 2:
			if get_node("RippleSpawn").get_time_left() <= 0:
				get_node("RippleSpawn").set_wait_time( 0.3 + ((movespeed - lvlen) / movespeed) * 0.7)
				get_node("RippleSpawn").start()
		else:
			get_node("RippleSpawn").stop()

	else:
		get_node("RippleSpawn").stop()
		lv -= lv * 0.9 * step
		av -= av * 0.9 * step

Bingo, We have the control functions in the bag.
The real fun now is to change this part of the code to our liking (if needed at all).

Printing every possible combinations of ABC (Swift 2.2 )

Posted on Updated on

I had time this evening .. so I figured why not dig up some example code I copied from a tutorial online and modify it to show every possible combinations of the letters A, B and C.

Only this time instead of showing through a terminal I would print it on an iPhone app. So here it is ..

スクリーンショット 2016-03-28 21.19.43

Source code:

import UIKit

class ViewController: UIViewController
{
    @IBOutlet weak  var totalPermutations: UILabel!         // print total permutations count of ABC
    @IBOutlet weak  var _comboTextView: UITextView!         // print every combination of ABC
    @IBOutlet       var _outputLabel: UILabel!
                    var _currentCount = 0

    let combinationsArray: [String] = ["A", "B", "C"]

    /**
     * Initialization
     */
    override func viewDidLoad()
    {
        super.viewDidLoad()
        printCombinations()
    }

    /**
     * Print every combination of ABC
     */
    func printCombinations()
    {
        var totalCombinations = 0
        var str: String = ""
        for letter in combinationsArray {
            for nextLetter in combinationsArray {
                for nextNextLetter in combinationsArray {
                    totalCombinations++
                    str += (letter + nextLetter + nextNextLetter + "\n")
                }
            }
        }
        totalPermutations.text = ("Permutations: " + String(totalCombinations))
        _comboTextView.text = str
    }

    /**
     * Memory warning
     */
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }

    /**
     * Start counting
     */
    @IBAction func addOneButton(sender: UIButton)
    {
        _currentCount++
        _outputLabel.text = "クリック回数は:\(_currentCount)"
        _outputLabel.textColor = UIColor.redColor()
    }
}

Edit: Added total permutations counter
Github: https://github.com/benji011/counterApp

Random PHP fun

Posted on

Decided to cook up a very quick & easy piece of code in PHP that prints from 1 to 30 and if any number in that range is divisible by 3 then print “Science”.

  for($i = 0; $i < 31; $i++) {
    if ($i == 0) continue;
    $science = ( ($i % 3) == 0) ? "Science" : $i;
    echo $science . "<br>";
  }

Result:

1
2
Science
4
5
Science
7
8
Science
10
11
Science
13
14
Science
16
17
Science
19
20
Science
22
23
Science
25
26
Science
28
29

SQLSTATE[HY000] [2002] Connection refused – Laravel 5

Posted on

laravel-slant

I’ve started to move forward with Web development but first I needed to study some kind of framework. I picked Laravel 5 with PHP and MySQL (for no particular reason whatsoever).

Anyway I followed the instructions and then entering the command php artisan migrate I ran into this error:

  [PDOException]
  SQLSTATE[HY000] [2002] Connection refused

great .. Well this tells me my SQL configurations haven’t been set up. Which is bang on the spot because I don’t have any database setup. So setting up is pretty easy:

Use this guide ( http://coolestguidesontheplanet.com/get-apache-mysql-php-and-phpmyadmin-working-on-osx-10-11-el-capitan/#mysql )

Installation all done. Moving along ..

  [PDOException]
  SQLSTATE[HY000] [2002] Connection refused

Same error.
Again, MySQL hasn’t been set up … well okay I guess I didn’t link it. So I go back to the page from the URL I just posted, hit this in my terminal:

export PATH="/usr/local/mysql/bin:$PATH"

Now I’ve linked my MySQL path to my Bash profile. Then I go back to my current directory for Laravel ( /Users/benji/Sites/application ) and enter:

➜  application source ~/.bash_profile
➜  application  php artisan migrate
                                                     
  [PDOException]                                     
  SQLSTATE[HY000] [1049] Unknown database 'laravel'  

… Well MySQL is now connecting but I don’t have a database called Laravel ( which I configured in my database.php file ). No problem. Just create it manually.

➜  application  mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 646
Server version: 5.7.9 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE laravel;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| laravel            |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> use laravel
Database changed
mysql> show tables;
Empty set (0.00 sec)

Should be good now. Try migrate again:

➜  application  php artisan migrate
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2016_02_06_074417_create_tasks_table
➜  application  mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 665
Server version: 5.7.9 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| laravel            |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

mysql> use laravel;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-------------------+
| Tables_in_laravel |
+-------------------+
| migrations        |
| password_resets   |
| tasks             |
| users             |
+-------------------+
4 rows in set (0.00 sec)

And now we’re done. Excellent! moving along.

Long awaited update

Posted on

It’s been a while since I posted anything on my blog. Truth is I haven’t had any time for myself to do anything creative.

You know, At the start of 2016 I promised myself that I will do what I want to make myself happy … within Gods will. And I’m going to do just that.

Stay tuned for more updates later .. if you’re a follower of my blog. Peace to all and happy belated new year! 🙂

Unity 3D: Calculating something is within viewing range (C#)

Posted on Updated on

If you ever want to calculate the viewing angle of a character you “could” use Quaternion.Euler to calculate the x, y & z coordinates .. which would probably look something like:

float viewAngle = 90.0f;
// ...
Vector3 direction = Quaternion.Euler(0.0f, 90.0f, 0.0f) * (gameObject.transform.localPosition - this.transform.localPosition).normalized;
float dot = Vector3.Dot(CurrentDirection, direction);
if(dot < viewAngle)  
{
	// not in viewing angle .. so exit loop and do something else
	continue;
}

But i think this looks more complicated than it should be. So instead, use Vector3.Angle to get the forward position of your character already, subtract it from an enemy character/obstacle/whatever then check whether it is less than or equal to the viewing angle. You’ll know when something is in front of your character and within viewing ange or

//  Can now see
float viewAngle = 90.0f;
// ...
if(Vector3.Angle(transform.position - gameObject.transform.position, transform.forward) <= viewAngle)
{
	// do something
}

Git: Deleting stubborn untracked files

Posted on

Alright I’ve ran into this problem way too many times and not kept a note on this so to save myself the trouble (and to the poor donkeys out there who are on the same boat) I’m making a note now so I won’t forget … and to help everybody out there.

Lets say you’ve finished on your assignment and you hit git status before pushing your work into your remote repository. You get something like this:

Benji$  git status
On branch feature/LOLMACHINE
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	deleted:    Animations/nyancat.meta
	modified:   LOL_Game.unity

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	../ProjectSettings/stubbornfile.asset
	../ProjectSettings/stubbornfile2.asset
	../ProjectSettings/stubbornfile3.asset

Try as you might Git reset HEAD and Git reset doesn’t work.

Luckily you can get rid of untracked files using the simple git clean -xf

If you feel compelled to remove everything including the directories you worked on but might not necessarily be needed then you can use git clean -df and BOOM, all is good again.