ゲームプログラム・サンプルプログラム集 (トップページに戻る)
背景スクロール(遠い背景と近い背景)
実装イメージ

・プレイヤーは特に移動せずに固定座標に描画しています。
・背景画像を2枚並べて描画して、画面左に消えたら1画面分右に戻しています。
・遠い空背景と近い地面背景で同じ処理をしていますが、移動スピードだけ違います。
サンプルプログラム

#include "DxLib.h"

#define BG_SIZE_W	500			// 背景画像の横幅

// プレイヤー画像ハンドル
int PlayerGraph;

// 空画像ハンドル
int SkyGraph;
// 空座標
int SkyX;
int SkyY;

// 地面画像ハンドル
int GroundGraph;
// 地面座標
int GroundX;
int GroundY;

// ==============================
// *** 初期化処理 ***
// ==============================
void Game_Init()
{
	// プレイヤー画像の読み込み
	PlayerGraph = LoadGraph( "プレイヤー.png" );

	// 空画像の読み込みと初期座標の設定
	SkyGraph = LoadGraph( "背景.png" );
	SkyX = 0;
	SkyY = 0;

	// 背景画像の読み込みと初期座標の設定
	GroundGraph = LoadGraph( "地面.png" );
	GroundX = 0;
	GroundY = 150;
}
// ==============================
// *** 更新処理 ***
// ==============================
void Game_Update()
{
	// 空画像を画面左に移動させる
	SkyX -= 1;
	// 画面左に全部消えたら
	if( SkyX < -BG_SIZE_W ){
		// 画像サイズ分右に戻す
		SkyX += BG_SIZE_W; 
	}

	// 地面画像も同じように(移動スピードが違う)
	GroundX -= 3;
	if( GroundX < -BG_SIZE_W ){
		GroundX += BG_SIZE_W; 
	}
}
// ==============================
// *** 描画処理 ***
// ==============================
void Game_Draw()
{
	// 空の描画
	DrawGraph( SkyX, SkyY, SkyGraph, TRUE );
	DrawGraph( SkyX + BG_SIZE_W, SkyY, SkyGraph, TRUE );

	// 地面の描画
	DrawGraph( GroundX, GroundY, GroundGraph, TRUE );
	DrawGraph( GroundX + BG_SIZE_W, GroundY, GroundGraph, TRUE );

	// プレイヤーの描画
	DrawGraph( 100, 100, PlayerGraph, TRUE );
}
// ==============================
// *** 終了処理 ***
// ==============================
void Game_End()
{
	DeleteGraph( PlayerGraph );
	DeleteGraph( SkyGraph );
	DeleteGraph( GroundGraph );
}

// ******************************
// メイン関数
// ******************************
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	ChangeWindowMode( TRUE );
	SetGraphMode( 500, 200, 16 );
	if( DxLib_Init() == -1 ){
		return -1;
	}
	SetDrawScreen( DX_SCREEN_BACK );

	Game_Init();		// *** 初期化処理 ***

	while( ProcessMessage() == 0 && CheckHitKey( KEY_INPUT_ESCAPE ) == 0 ){
		Game_Update();	// *** 更新処理 ***

		ClearDrawScreen();
		Game_Draw();	// *** 描画処理 ***
		ScreenFlip();
	}

	Game_End();			// *** 終了処理 ***
	DxLib_End();
	return 0;
}