子弹类:
Bullet* Bullet::create(float attack,Vec2 startPos,Vec2 endPos) { Bullet* pRet = new Bullet(); pRet->_attack = attack; //攻击力 pRet->_startPos = startPos; //起点和终点 pRet->_endPos = endPos; if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { delete pRet; pRet = NULL; return NULL; } }
bool Bullet::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); _bullet = Sprite::create("pd/baizhanche.png"); Vec2 dtPos = _endPos - _startPos; float rotation = CC_radians_TO_degrees(Vec2::angle(dtPos,Vec2(1,0))); //弧度转为角度,现在是点击点与起点和横轴的夹角 if (dtPos.y > 0) //点击的点在武将位置的上方 rotation = -rotation;
float dt = _endPos.distance(_startPos); _bullet->setRotation(_bullet->getRotation() + rotation); this->setPosition(_startPos); _bullet->setPosition(Vec2(0,0)); auto done = CallFuncN::create([=](Ref* ref) { this->removeFromParentAndCleanup(true); }); this->runAction(Sequence::create(MoveBy::create(2,dtPos*(visibleSize.width * 2 / dt)),done,NULL)); addChild(_bullet,0); return true; }
Rect Bullet::getRect() { <span style="white-space:pre"> </span>Rect a = _bullet->getTextureRect(); <span style="white-space:pre"> </span>float minX = this->getPosition().x - a.getMaxX() * 0.5; //最左的边 <span style="white-space:pre"> </span>float minY = this->getPosition().y - a.getMaxY() * 0.5; //最下的边 <span style="white-space:pre"> </span>Rect b = Rect(minX,minY,a.getMaxX(),a.getMaxY()); <span style="white-space:pre"> </span>return b; }
另如果想实现匀速运动(因为Moveto MoveBy都是按照固定的时间来运动):
void Bullet::kaihuo(Point pos) { float xdistance = (pos.x - this->getPosition().x); float ydistance = (pos.y - this->getPosition().y); _radii = atan2(ydistance,xdistance); scheduleUpdate(); } void Bullet::update(float dt) { _time += dt; this->setPosition(Vec2(_pos.x + BULLETSPEED * _time * cos(_radii),_pos.y + BULLETSPEED * _time * sin(_radii))); }
另:
getBoundingBox 中得 Size.width .height 显示图片真实大小 (考虑缩放和不缩放)
getContentSize 纹理图片大小
getTextureRect 当前的纹理在总纹理的位置 (不考虑 缩放不缩放)
图片有缩放 就用 getBoundingBox ,不考虑缩放用 getContentSize