[GODOT] Animate camera depending on touch screen events (C#)


If you develop a 2D game for mobile, like a RPG game seen from top (Zelda like for instance), and you want to navigate on your map just by dragging the screen, here is the simple way to implement it in GODOT.


In your level scene you have to add a "Camera" Node and make it the current one:

    public override void _Ready()
    {
        // Ensure the camera is set as current
        Current = true;
    }



Then create the associated Camera script (in this example in C#). You have to handle Godot input events to animate the camera. The events to manage are:

- InputEventScreenTouch

- InputEventScreenDrag


The goal is to determinate the delta amount of  horizontal & vertical spaces that have been dragged by the user. You can see an example of handling these events in the following code snippet (camera script): 

using Godot;
using System;

public partial class camera : Camera2D
{
	private Vector2 _touchStartPosition = new Vector2();
	private bool _isDragging = false;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		// ensure camera is the active one
		MakeCurrent();
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public override void _Input(InputEvent @event)
	{
    	// manage event to know when screen dragging starts:
		if (@event is InputEventScreenTouch)
		{
			if(@event.IsPressed() == true)
			{
				_touchStartPosition = (@event as InputEventScreenTouch).Position;
				_isDragging = true;
            }
			else
			{
				_isDragging = false;
			}
		}
        // manage the current dragging operation:
		else if (@event is InputEventScreenDrag)
		{
            if (_isDragging)
            {
				var dragEvent = (@event as InputEventScreenDrag);

                // Calculate the movement delta
                Vector2 delta = dragEvent.Position - _touchStartPosition;

				// Move the camera in the opposite direction of the touch movement
				this.Position -= delta;

                // Update the start position for the next delta calculation
                _touchStartPosition = dragEvent.Position;
            }
        }
    }
}


Comments

Popular posts from this blog

EMGU with Xamarin Forms guide [part 1]

Xamarin Forms essential: FFImageLoading, manage your images

[SocialCut] released! Make instagram grids, panorama and more