Skip to content

Instantly share code, notes, and snippets.

@megarubber
Created March 22, 2023 01:31
Show Gist options
  • Save megarubber/0d9b8b3c3056e9e990ead0edaea3f510 to your computer and use it in GitHub Desktop.
Save megarubber/0d9b8b3c3056e9e990ead0edaea3f510 to your computer and use it in GitHub Desktop.
Ball collision gyroscope flutter
import 'package:flutter/material.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'dart:math';
class Jogo extends StatefulWidget {
const Jogo({Key? key}) : super(key: key);
@override
State<Jogo> createState() => JJ();
}
class JJ extends State<Jogo> {
static const double maxSpeed = 30;
final testeKey = GlobalKey();
final playerKey = GlobalKey();
double playerX = 200;
double playerY = 100;
double speed = 10;
double xVel = 0;
double yVel = 0;
int onCollisionWalls(double x, double y) {
RenderBox? box1 = playerKey.currentContext!.findRenderObject() as RenderBox;
final size1 = box1.size;
final position1 = box1.localToGlobal(Offset.zero);
RenderBox? box2 = testeKey.currentContext!.findRenderObject() as RenderBox;
final size2 = box2.size;
final position2 = box2.localToGlobal(Offset.zero);
final testX = (position1.dx + size1.width > position2.dx && position1.dx < position2.dx + size2.width);
final testY = (position1.dy + size1.height > position2.dy && position1.dy < position2.dy + size2.height);
final testXPrev = (position1.dx + size1.width + x > position2.dx && position1.dx + x < position2.dx + size2.width);
final testYPrev = (position1.dy + size1.height + y > position2.dy && position1.dy + y < position2.dy + size2.height);
if(testXPrev && testYPrev) {
if(!testX) return 3;
else if(!testY) return 2;
return 1;
}
return 0;
}
@override
void initState() {
super.initState();
gyroscopeEvents.listen((GyroscopeEvent event) {
xVel += (-event.z * speed);
yVel += (event.x * speed);
double xS = min(maxSpeed, max(-maxSpeed, xVel));
double yS = min(maxSpeed, max(-maxSpeed, yVel));
int col = onCollisionWalls(xS, yS);
if(col == 1) {
xVel = 0;
yVel = 0;
} else if(col == 2) {
playerX += xS;
yVel = 0;
} else if(col == 3) {
playerY += yS;
xVel = 0;
} else {
playerX += xS;
playerY += yS;
}
setState(() { });
});
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
body: SafeArea(
child: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(20),
child: Stack(
children: [
Positioned(
left: 40,
top: 100,
key: testeKey,
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
color: Colors.yellow,
)
),
),
Positioned(
key: playerKey,
left: playerX,
top: playerY,
child: Container(
width: 70,
height: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(80),
color: Colors.red
)
),
)
]
)
)
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment