#Blog

Blog articles on programming and problems focused on iOS and some web. I also write stories on my travel and hiking pursuits outside my work.

How to detect click inside StaticBody2D in Godot Game Engine?

by

A simple approach to detect mouse click in our game is to intercept input event in in-built _input method. Let’s intercept the input.


extends StaticBody2D
func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT and event.pressed:
            print(“A click!”)

The problem is that input detection is registered all over the viewport. Let me explain. I have a Sprite child node inside StaticBody2D node. My intention is to detect mouse input over the visible sprite only. In our 2D game we may want to select an object in our world with mouse and do some interaction with it. In this case mouse input is been registered outside the Sprite node.Note that our script is attached to StaticBody2D. As a result this node has to have a shape, so the example has a collision shape as a child. We are trying to keep Sprite node loosely coupled from the logic. Documentation clearly says that StaticBody2D is not intended to move. This makes perfect for objects like trees in the game.

Let’s come back to our problem. My assumption for the behaviour would be that StaticBody2D is shapeless. Yes, we did add a collision shape so it mouse input should be triggered only over defined collision shape. However, StaticBody2D is behaving shapeless and mouse input is registered all over the screen.


A simple approach I discovered is two steps.

CONTINUE READING


How to Set and Restrict the Camera 2d Boundary in Godot Game engine

by

I have been learning and practicing Godot game engine by watching free high quality video series from HeartBeast. I really want you to go and watch this RPG tutorial series to learn practical fundamentals of Godot engine. In part-20 of the series we learned about setting up camera and make camera follow the player around the level. It is very easy in Godot.

Above tutorial video lets you learn to easily setup player Camera2D. One thing was missing and I took a challenge exercise where camera stops following the player when player is near the edge or boundary of the level. Currently camera moves with player and vast empty space is visible when player is near boundary of the level.

My solution is based on existing type of game world I am working with.

CONTINUE READING


How to Change Color of UISwitch in Off State

by

There is no given individual property available to change the color of UISwitch in “off” state. We have the property to change color for “on” state called onTintColor. For "off" sate We can achieve by changing certain combination of properties to UISwitch.

By default background color of UISwitch is clear. We change background color to new color. Remember this changes the background color of UISwitch, and this will result in rectangle solid background color. Our UISwitch must have rounded corners and to match that we update the corner radius of UISwitch. That is it.

Optional step is to update tintColor of UISwitch to match the background color to keep it even.

First way, Inheritence - creating custom UISwitch class. In this example code I am exposing designable property for easy use in our storyboard.


class CustomSwitch: UISwitch{
    @IBInspectable var offTintColor: UIColor? {
        didSet {
            let minSide = min(bounds.size.height, bounds.size.width)
            layer.cornerRadius = minSide / 2
            backgroundColor = offTintColor
            tintColor = offTintColor
        }
    }
}

CONTINUE READING


How To Optimize Laravel Code Eloquently With UpdateOrCreate()

by

In beginning of my Laravel learning, I did write more lines of code to perform my task than I write now. I started learning to adopt more eloquent ways of coding for Laravel encourages us to write. One simple task I performed by writing this many number of lines:


$place = PlaceModel::where('id', "132")->first();
if(isset($place))
{
  $place->update(['name' => 'Place Name', 'address' => 'Place Address',]);
}
else
{
  $place = PlaceModel::create([
    'name' => 'Place Name',
    'address' => 'Place Address',
  ]);
}

This many lines of code can be optimised to single statement of line in Laravel Eloquent way. This is ome of the ways to optimize eloquent query on Laravel:

CONTINUE READING


प्रोग्रामिंग: एक परिचय (An Introduction to Programming in Nepali)

by

यस ट्यूटोरियलको लक्ष्य छ तपाईंलाई सकेसम्म चाँडो त्यो चरणमा पुग्ने प्रयास गर्न जहाँ तपाईं उपयोगी प्रोग्रामहरू लेख्न सक्नुहुनेछ। नयाँ प्रोग्रामिंग भाषा सिक्ने एक मात्र तरिका यसमा प्रोग्रामहरू लेख्नु हो। तपाईले प्रोग्राम पाठ कहिँ लेख्न, यसलाई सफलतापूर्वक कम्पाइल गर्न, लोड गर्न, चलाउन, र आउटपुट फेला पार्न सक्षम हुनुपर्दछ।

मैले सरल कारणले गर्दा यो ट्यूटोरियल श्रृंखला को लागी जाभास्क्रिप्ट(javascript) भाषा छानिएको छु। जाभास्क्रिप्ट कोड सिक्न र गर्न सजिलो छ। यसले तपाईंको सिक्ने समयको बचत गर्न सक्दछ। जाभास्क्रिप्ट हरेक आधुनिक वेब ब्राउजरमा स्थापित हुन्छ, त्यसैले तपाईं अहिले जाभास्क्रिप्टमा प्रोग्रामिंग सुरु गर्न सक्नुहुनेछ उही ब्राउजरमा जुन तपाईं यो लेख पढ्न प्रयोग गर्दै हुनुहुन्छ। यदि तपाईं गुगल क्रोम प्रयोग गर्दै हुनुहुन्छ भने, केवल “view” मेनूमा जानुहोस्, “developer” उप-मेनूमा क्लिक गर्नुहोस्, र तपाईंले “javascript console” खोल्ने विकल्प देख्नुहुनेछ।

हामी यी आधारभूत कुरामा ध्यान दिनेछौं: भ्यारीएबल र constants, अंकगणित(arithmetic), control-flow र फंक्शन।

CONTINUE READING


How to Detect Backspace Event in UITextfield and UITextview?

by

In past I have used shouldChangeCharactersInRange delegate method to intercept the change in characters and make a near guess if it was delete-backspace that was tapped by the user. Guess was based on the nature of replacement character provided in method. If replacement character resembled the special escape character "\b" indicating backspace or empty character when view is already empty.

I felt above direction was a bit hacky. I found that based on response logic I was trying to write was giving me side effect of cursor always jumping to the end of text. For example when I tapped in between the characters of text to set the cursor in position and when I pressed backspace in keypad - I detected the event and did my processing to do some changes to text of UITextField and returned false.

What is the clean solution then?

CONTINUE READING


How to add a completion handler block for when I pop UIViewController?

by

Today I pondered about a problem which I had overlooked in past. How to add a completion handler block for when I pop UIViewController?


navigationController?.popViewController(animated: true)

In modal transition, dismissViewControllerAnimated, apple offers an option to call a completion block when dismissal of modal is finished. This is quite handy for various situations where you need to perform certain task like signalling a delegate about something when controller is removed from top of navigation or window.


dismiss(animated: true) {
}

Something similar isn’t offered directly in api for pop and push transitions. We do have been provided with viewDidAppear like methods that may be used to get things certain way. Flexibility and easiness that comes from completion handler of transition is unbeaten.

What we don’t have available from api can be solved by using core animation’s transactions. We group multiple animation related changes together and ensure all changes are run at the same time.

This is fine but how to notify when animation changes are finished?

CONTINUE READING


How to add a custom section header to a table view in Swift

by

Two of a simplest approaches is to use delegate method viewForHeaderInSection and return header view in a form of UIView itself or Custom class inheriting UITableViewHeaderFooterView.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

Asks the delegate for a view to display in the header of the specified section of the table view.

Using custom header view in the form of just UIView is good when we have something more than text to show in header.


override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor.systemBlue
    return headerView
}

The other way - more flexible - is to have custom class of UITableViewHeaderFooterView. This approach gives much flexibility to have custom states and properties to handle for complex headers. Example code:

CONTINUE READING


UIToolbar for keyboard inputAccessoryView gives Layout Constraint Errors

by

UIToolbar is very useful control for our input fields for example when we need some action buttons above keypad for input whose keypad type is UIKeyboardType.phonePad. UIKeyboardType.phonePad doesn’t come up with any return key button to dismiss as of now. A simple UIToolbar is very sufficient to provide a button for user to dismiss or do something else.

UIToolbar

A control that displays one or more buttons along the bottom edge of your interface.

The simple code to add UItoolbar to textfield:


let flexibleButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let done = UIBarButtonItem(title: "Dismiss", style: .done, target: self, action: #selector(doneKeypadTapped))
let bar = UIToolbar()
bar.items = [flexibleButton, done]
bar.sizeToFit()
phonePadTextfield.inputAccessoryView = bar

Now above code does give layout-constraints error indicating that few constraints are not satisfying each other and breaking the layout. It will not break the app in the sense but it does give sense of unease to a developer.

Small snippet from the contraint-error:


<NSLayoutConstraint:0x6000023bec60 ‘TB_Trailing_Trailing’ H:[_UIModernBarButton:0x7fb8bb990f20’Dismiss’]-(20)-|   (active, names: ‘|’:_UIButtonBarButton:0x7fb8bb98e100 )>

CONTINUE READING


How to find out distance between gps location coordinates in Swift?

by

A very simple way to calculate the distance between two given CLLocationCoordinate2D is to first convert them to MKMapPoint which represents two-dimensional point on map.


let point1 = MKMapPoint(clcoordinate1)
let point2 = MKMapPoint(clcoordinate2)

Now, we just use distance(to:) method to receive the distance in meters. Below is the code:

CONTINUE READING


Recommended posts