Skip to main content

尝试用pixi.js创建小游戏

在React里面使用pixi.js


写出下面的代码就可以创建出一个全屏的pixi.js画布

const PixiCanvas = () => {
const pixiContainerRef = useRef(null);

useEffect(() => {
const app = new PIXI.Application({resizeTo: window})

pixiContainerRef.current.appendChild(app.view);

return () => {
app.destroy(true);
}
}, []);

return <div ref={pixiContainerRef} />;
}


加入一个container, 将背景图片挂载到这个container上面,然后加到场景pixijs app里面

useEffect(() => {
const app = new PIXI.Application({ resizeTo: window });

const container = new PIXI.Container();

// background image
const backgroundTexture = PIXI.Texture.from(backgroundImage);
const backgroundSprite = new PIXI.Sprite(backgroundTexture);

const resizeBackground = () => {
backgroundSprite.width = window.innerWidth;
backgroundSprite.height = window.innerHeight;
};

// set position of the background picture
backgroundSprite.position.set(0, 0);
resizeBackground();

window.addEventListener('resize', resizeBackground);

container.addChild(backgroundSprite);
app.stage.addChild(container);

pixiContainerRef.current.appendChild(app.view);


loadAllImages(app);
return () => {
window.removeEventListener('resize', resizeBackground);
app.destroy(true);
}
}, []);


设置缩放大小

backgroundSprite.scale.set(2);


设置透明度

backgroundSprite.alpha = 0;

或者

backgroundSprite.visible = false;


滤镜

backgroundSprite.tint = 0xff0000;


居中

sprite.anchor.set(0.5);


为物体设置交互

sprite.interactive = true;
sprite.on("mousedown", onMouseDragStart, this)

然后在onMouseDragStart里面可以获取到e,即为event

我的游戏中,有背景的container,还有放拼图的container。因此,每次移动需要计算的offset为鼠标移动的距离加上原本的坐标。

所以在鼠标点下去的时候,可以使用以下的函数:

function onMouseDragStart(e) {
// 1. remember the position of the mouse cursor
this.touchPosition = {x: e.data.global.x, y: e.data.global.y}
// 2. set the dragging state for current sprite
this.dragging = true;
this.zIndex = 1;
}

记录下鼠标点下去的初始的点。

然后在移动的时候:

function onMouseMove(e) {
if (!this.dragging) {
return;
}
// console.log("this: ", this);
// 1. get the coordinate of the cursor
const currPosition = {x: e.data.global.x, y: e.data.global.y};

// 2. calculate offset
const offsetX = currPosition.x - this.touchPosition.x;
const offsetY = currPosition.y - this.touchPosition.y;

// 3. apply the result to this sprite
const {x, y} = this.field;
const newX = x + offsetX;
const newY = y + offsetY;
this.position.set(newX, newY);
}

计算并设置物体最终的位置。


然后在鼠标松开或者鼠标移开物体的时候,将dragging的state设置为false,并且复原位置:

function onMouseUp(e) {
this.dragging = false;
this.zIndex = 0;
this.position.set(this.field.x, this.field.y);
}

上面是整体思路,需要绑定许多事件:

sprite.on("mousedown", onMouseDragStart.bind(sprite));
sprite.on("touchstart", onMouseDragStart.bind(sprite));
sprite.on("mousemove", onMouseMove.bind(sprite));
sprite.on("touchmove", onMouseMove.bind(sprite));
sprite.on("mouseup", onMouseUp.bind(sprite));
sprite.on("mouseupoutside", onMouseUp.bind(sprite));
sprite.on("touchend", onMouseUp.bind(sprite));
sprite.on("touchendoutside", onMouseUp.bind(sprite));


在实现的过程中,我发现拖拽物体有时候拖拽无法穿过另外一个物体。然后发现穿不过去的物体,都是在我拖拽的物体的上方。说明z-index是大于我拖拽的物体的。

要实现成功拖拽,可以在拖拽开始的时候设置z-index为1,然后拖拽结束的时候重新设置为0。

并且需要在初始化拼图容器的时候,加上这个属性: 

puzzleContainer.sortableChildren = true

使其能够重新对index进行排序。


在pixi.js中,如果z-index一样,那么后生成的物体会在前面生成的物体之上。并且前生成的物体无法穿过后生成的物体。


相对位置

在我的拼图游戏中,背景的容器为一个容器,其中包含一个拼图的容器。而每次事件获取到的是global position,但是我的拼图用的都是相对于拼图容器的位置。

可以使用

const localPosition = globalPuzzleContainer.toLocal(new PIXI.Point(e.data.global.x, e.data.global.y));

来从global position获取到拼图容器中的位置


声音

要想在pixi.js中使用声音,可以使用pixi-sound

npm install pixi-sound

然后使用下面的语句来使用:

import sound from "pixi-sound";
import backgroundSound from "./sound/background-sound.mp3";
sound.add("backgroundSound", backgroundSound);
sound.play('backgroundSound');


动画

可以使用npm来安装

npm install @tweenjs/tween.js










Comments

Popular posts from this blog

Templates

  Template - Polymorphism is the ability of the same code to operate on different types. This ability to operate on multiple types reduces code duplication by allowing the same piece of code to be reused across the different types it can operate on. - Polymorphism comes in a variety of forms. What we are interested in at the moment is parametric polymorphism, meaning that we can write our code so that it is parameterized over what type it operates on.  -That is, we want to declare a type parameter T and replace int with T in the above code. -Then, when we want to call the function, we can specify the type for T and get the function we desire. C++ provides parametric polymorphism through templates. Templated Functions - We can write a templated function by using the keyword template followed by the template parameters in angle brackets (<>). - Unlike function parameters, template parameters may be types, which are specified with typename where the type of the parameter wo...

useMemo的使用场景

 useMemo是用来缓存 计算属性 的。 计算属性是函数的返回值,或者说那些以返回一个值为目标的函数。 有些函数会需要我们手动去点击,有些函数是直接在渲染的时候就执行,在DOM区域被当作属性值一样去使用。后者被称为计算属性。 e.g. const Component = () => { const [ params1 , setParams1 ] = useState ( 0 ); const [ params2 , setParams2 ] = useState ( 0 ); //这种是需要我们手动去调用的函数 const handleFun1 = () => { console . log ( "我需要手动调用,你不点击我不执行" ); setParams1 (( val ) => val + 1 ); }; //这种被称为计算属性,不需要手动调用,在渲染阶段就会执行的。 const computedFun2 = () => { console . log ( "我又执行计算了" ); return params2 ; }; return ( < div onClick = { handleFun1 } > //每次重新渲染的时候我就会执行 computed: { computedFun2 () } </ div > ); }; 上面的代码中,在每次点击div的时候,因为setParams1的缘故,导致params1改变,整个组件都需要重新渲染,也导致comptedFunc2()也需要重新计算。如果computedFunc2的计算量很大,这时候重新计算会比较浪费。 可以使用useMemo: const Com = () => { const [ params1 , setParams1 ] = useState ( 0 ); const [ params2 , setParams2 ] = useState ( 0 ); //这种是需要我们手动去调用的函数 const handleFun1 ...

Valgrind

  Using Valgrind to check memory How to use Valgrind -To valgrind the program, run the valgrind command and give it our program name as an argument. -For example, if we want to run ./myProgram hello 42, we can simply run Valgrind ./myProgram hello 42.  Uninitialized Values -When we run the program, we may use uninitialized values. It needs to be fixed. Valgrind can tell us about the use of uninitialized values. But it only tell when the control flow of the program depends on the unitialized value. For example, uninitialized value appears in the conditional expression of an if, or a loop, or in the switch statement. -If we want to know where the uninitialized value is from, we can use Valgrind    --track-origins=yes ./myProgram -Using -fsanitize=address can find a lot of problems that Memcheck cannot.  -We can use Valgrind with GDB to debug. We can run: --vgdb=full --vgdb-error=0., then Valgrind will stop on the first error that it encounters and give control to ...