반응형
flutter flame을 이용해서 2D 게임 제작을 해 보려고 합니다.
flutter flame 기본은 아래 블로그를 참고 바랍니다.
2024.04.30 - [프로그램 개발해서 돈벌기/flutter] - [초보자 게임 만들기 기초] flutter flame 구조와 사각형 위에서 아래로 떨어뜨리기
[초보자 게임 만들기 기초] flutter flame 구조와 사각형 위에서 아래로 떨어뜨리기
flutter flame을 이용해서 2D 게임 제작을 해 보려고 합니다. 우선 flutter에서 flame을 사용하는 가장 간단한 기본 코드 구조를 보겠습니다. import 'package:flutter/material.dart';import 'package:flame/game.dart';void m
direction-to-money.tistory.com
기본 구조와 이동에 대해 알았다는 가정하에 설명하겠습니다.
두 사각형(파란색, 빨간색)이 위, 아래에서 중앙으로 이동하다 충돌 시 반대로 튕기기 샘플 코드를 작성해 보겠습니다.
"onCollision"에서 충돌을 처리합니다.
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: GameWidget(game: MyGame()),
);
}
}
class MyGame extends FlameGame with HasCollisionDetection {
late MovingBox _box1;
late MovingBox _box2;
@override
Future<void> onLoad() async {
super.onLoad();
_box1 =
MovingBox(Vector2(size.x / 2 - 25, 0), Vector2(0, 100), Colors.blue);
_box2 = MovingBox(
Vector2(size.x / 2 - 25, size.y - 50), Vector2(0, -100), Colors.red);
add(_box1);
add(_box2);
debugMode = true;
}
}
class MovingBox extends PositionComponent
with CollisionCallbacks, HasGameRef<MyGame> {
static const double boxSize = 50;
Vector2 velocity;
final Color color;
MovingBox(Vector2 position, this.velocity, this.color)
: super(
position: position,
size: Vector2(boxSize, boxSize),
anchor: Anchor.topLeft);
@override
Future<void> onLoad() async {
super.onLoad();
add(RectangleHitbox());
}
@override
void update(double dt) {
super.update(dt);
position.add(velocity * dt);
if (position.y < 0) {
position.y = 0;
velocity.y = -velocity.y;
} else if (position.y > gameRef.size.y - boxSize) {
position.y = gameRef.size.y - boxSize;
velocity.y = -velocity.y;
}
}
@override
void onCollision(Set<Vector2> points, PositionComponent other) {
super.onCollision(points, other);
if (other is MovingBox) {
// Reverse the velocities of both boxes
velocity.y = -velocity.y;
//other.velocity = tempVelocity;
// Adjust positions slightly to prevent them from sticking together
if (velocity.y > 0) {
position.y += 2; // Move slightly in the direction of the new velocity
} else {
position.y -= 2; // Move slightly in the direction of the new velocity
}
}
}
@override
void render(Canvas canvas) {
final paint = Paint()..color = color;
canvas.drawRect(size.toRect(), paint);
}
}
실행 화면은 DartPad에서 동작한 결과입니다.
반응형
'프로그램 개발해서 돈벌기 > flutter' 카테고리의 다른 글
[초보자 게임 만들기 기초] flutter flame 구조와 사각형 위에서 아래로 떨어뜨리기 (0) | 2024.04.30 |
---|---|
유튜브 처럼 플레이 화면과 하단에 동영상 리스트가 보일때 동영상 리스트를 클릭 시 상단 플레이에 플레이 되게 만들기 (0) | 2024.03.04 |
flutter에서 자식 위젯이 부모 위젯 함수 호출하기 (0) | 2024.02.23 |
[flutter] Build failed due to use of deprecated Android v1 embedding. 를 만났을때 에러 수정 방법 (0) | 2024.01.31 |
flutter iOS에 권한 요청 방법 : 주소록에 접근 권한 요청하기 (0) | 2023.09.20 |
댓글