Cocos2d入门--3--向量的应用
小球向一个方向持续运动的Demo
HelloWorldScene.h
......
//设置一个protected的属性
protected:
cocos2d::Vec2 _vec;
......
HelloWorldScene.cpp
//这个是通过随机数设置向量的方向
_vec.set(random(-0.1f, 1.0f), random(-1.0f, 1.0f));
//通过normalize这个标准化函数,能够使得向量的大小为1
_vec.normalize();
auto dot = DrawNode::create();
dot -> drawDot(Vec2(0, 0), 5, Color4F(1.0f,1.0f,1.0f,1.0f));
addChild(dot);
dot -> setPosition(origin.x +
visibleSize.width/2,origin.y + visibleSize.height/2);
schedule([dot,this,origin,visibleSize](float f){
Vec2 nowVec = dot -> getPosition();
//判断小球碰壁反弹运动
if (nowVec.x<origin.x || nowVec.x>origin.x+visibleSize.width) {
_vec.x *= -1;
}
if (nowVec.y<origin.y || nowVec.y>origin.y+visibleSize.height) {
_vec.y *= -1;
}
dot->setPosition(nowVec+_vec*10);
}, "Test");