Reputation: 3
The problem I have is that when using the gyroscope in this game that I am developing in .NET MAUI, when I tilt the phone to the right the ship moves and goes over the screen, but when I want to move it to the left it stays stuck in the center
I tried hardcoding by entering the margins of my cell phone's screen, which would be 1080x2400 based on a solution someone gave me in which the ship only stays within those margins and if it tries to exceed this it would collide with the edge of the screen. But this didn't work.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Space_ships.MainPage">
<AbsoluteLayout x:Name="GameLayout">
<!-- Background Image -->
<Image Source="Resources/Images/space.jpg"
Aspect="AspectFill"
AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
AbsoluteLayout.LayoutFlags="All"/>
<!-- High Score Label -->
<Label x:Name="lblHighScore"
Text="HIGH SCORE"
FontSize="14"
TextColor="Yellow"
FontFamily="PressStart2P-Regular"
HorizontalOptions="Center"
VerticalOptions="Start"
AbsoluteLayout.LayoutBounds="0.5, 0.05, AutoSize, AutoSize"
AbsoluteLayout.LayoutFlags="PositionProportional"/>
<!-- Player Ship -->
<Image x:Name="PlayerShip"
Source="Resources/Images/Player/starship.png"
WidthRequest="60"
HeightRequest="60"
AbsoluteLayout.LayoutBounds="0.5, 0.9, AutoSize, AutoSize"
AbsoluteLayout.LayoutFlags="PositionProportional"/>
<!-- Enemy Ships Container -->
<AbsoluteLayout x:Name="EnemyShipsContainer"/>
</AbsoluteLayout>
using Microsoft.Maui.Controls;
using Plugin.Maui.Audio;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Maui.Devices.Sensors;
using Microsoft.Maui.Layouts;
namespace Space_ships
{
public partial class MainPage : ContentPage
{
private System.Timers.Timer gameTimer = new System.Timers.Timer(100);
private IAudioPlayer? backgroundMusicPlayer;
private int score = 0;
private const double screenWidth = 1080;
private const double screenHeight = 2400;
private double spaceshipSpeed = 100; // Sensibilidad ajustable para el movimiento
public MainPage()
{
InitializeComponent();
_ = SetupGameAsync();
}
private async Task SetupGameAsync()
{
score = 0;
lblHighScore.Text = "HIGH SCORE: " + score;
var audioManager = AudioManager.Current;
using var backgroundMusicStream = await FileSystem.OpenAppPackageFileAsync("515405__matrixxx__retro-gaming.wav");
backgroundMusicPlayer = audioManager.CreatePlayer(backgroundMusicStream);
backgroundMusicPlayer.Loop = true;
backgroundMusicPlayer.Play();
CreatePlayerShip();
StartGyroscope();
// Start the game timer
gameTimer.Elapsed += OnGameTick;
gameTimer.Start();
// Start enemy generation
StartEnemyGeneration();
}
private void CreatePlayerShip()
{
var playerShip = new Image
{
Source = "Resources/Images/Player/starship.png",
WidthRequest = 60,
HeightRequest = 60
};
// Place the ship in the horizontal center and near the bottom edge
AbsoluteLayout.SetLayoutBounds(playerShip, new Rect((screenWidth - 60) / 2, screenHeight - 240, 60, 60));
AbsoluteLayout.SetLayoutFlags(playerShip, AbsoluteLayoutFlags.None);
GameLayout.Children.Add(playerShip);
PlayerShip = playerShip;
}
private void StartGyroscope()
{
if (Gyroscope.Default.IsSupported)
{
Gyroscope.Default.ReadingChanged += Gyroscope_ReadingChanged;
Gyroscope.Default.Start(SensorSpeed.Game); // Use SensorSpeed.Game for greater precision
}
else
{
Console.WriteLine("Gyroscope is not compatible with this device.");
}
}
private void Gyroscope_ReadingChanged(object? sender, GyroscopeChangedEventArgs e)
{
// Handle changes in the gyroscope
Dispatcher.Dispatch(() =>
{
// AngularVelocity.Y is used to move the ship horizontally
var deltaX = e.Reading.AngularVelocity.Y * 10; // Adjust the multiplier as necessary
// Add debug to verify readings
Console.WriteLine($"Gyroscope Reading: AngularVelocity.Y = {e.Reading.AngularVelocity.Y}");
// update the position of the allied ship
UpdatePlayerPosition(deltaX);
});
}
private void MovePlayerShip(double deltaX)
{
// Calculates the new X position based on the motion detected by the gyroscope
var newX = PlayerShip.TranslationX + deltaX;
// Check the screen limits to prevent the ship from going off
if (newX < 0)
{
PlayerShip.TranslationX = 0;
}
else if (newX > (screenWidth - PlayerShip.WidthRequest))
{
PlayerShip.TranslationX = screenWidth - PlayerShip.WidthRequest;
}
else
{
PlayerShip.TranslationX = newX;
}
}
private void UpdatePlayerPosition(double deltaX)
{
var newX = PlayerShip.TranslationX + deltaX;
// Check the screen limits to prevent the ship from going off
if (newX < 0)
{
PlayerShip.TranslationX = 0;
}
else if (newX > (screenWidth - PlayerShip.WidthRequest))
{
PlayerShip.TranslationX = screenWidth - PlayerShip.WidthRequest;
}
else
{
PlayerShip.TranslationX = newX;
}
// Debugging to verify the new position
Console.WriteLine($"Player Position Updated: TranslationX = {PlayerShip.TranslationX}");
}
private void OnGameTick(object? sender, System.Timers.ElapsedEventArgs e)
{
Dispatcher.Dispatch(() =>
{
// Regular game update (if necessary)
});
}
private void GenerateEnemyShip()
{
var enemyShip = new Image
{
Source = "Resources/Images/Enemies/starshipdark.png",
WidthRequest = 50,
Rotation = 180,
HeightRequest = 50
};
Random rnd = new Random();
double xPosition = rnd.NextDouble() * (screenWidth - enemyShip.WidthRequest);
double yStartPosition = -enemyShip.HeightRequest; // Starts right off the screen
// Ensure that the enemy always starts within visible range
xPosition = Math.Clamp(xPosition, 0, screenWidth - enemyShip.WidthRequest);
double targetYPosition = screenHeight; // Posición final fuera de la pantalla
AbsoluteLayout.SetLayoutBounds(enemyShip, new Rect(xPosition, yStartPosition, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize));
EnemyShipsContainer.Children.Add(enemyShip);
// Animation for the enemy ship to fall
enemyShip.TranslateTo(xPosition, targetYPosition, 4000, Easing.Linear).ContinueWith(t =>
{
Dispatcher.Dispatch(() =>
{
EnemyShipsContainer.Children.Remove(enemyShip);
score += 20; // Increase the score for each ship dodged
lblHighScore.Text = "HIGH SCORE: " + score;
});
});
}
private void StartEnemyGeneration()
{
Dispatcher.DispatchDelayed(TimeSpan.FromMilliseconds(500), () =>
{
GenerateEnemyShip();
StartEnemyGeneration(); // Call recursively to continue generating ships
});
}
}
}
Upvotes: 0
Views: 47