首页 > 代码库 > cocos3 抛物线运动

cocos3 抛物线运动

#pragma once#include "cocos2d.h"USING_NS_CC;class Parabola:public ActionInterval{public:    static Parabola* create(const CCPoint& startPosition, const CCPoint& endPosition,         float angle, float g,float &return_duration);     //override    virtual Parabola* clone() const override;    virtual Parabola* reverse() const override;     virtual void update(float time) override;protected:    bool initWithDuration(float duration, const CCPoint& startPosition,         const CCPoint& endPosition, float angle, float g, float vx0, float vy0);protected:    float    m_vx0;    float    m_vy0;    Point    m_startPosition;    Point    m_endPosition;    float    m_angle;    float    m_dur ;    float    m_tan_a;    float    m_g;};
#include "Parabola.h"#define PIXELS_PER_METER 100Parabola* Parabola::create(const CCPoint& startPosition, const CCPoint& endPosition,                            float angle, float g,float &return_duration){    Parabola *pRet = new Parabola();    float vx0,vy0, x1, y1,  duration;    x1 = endPosition.x - startPosition.x;    y1 = endPosition.y - startPosition.y;    x1 /= PIXELS_PER_METER; //像素到米的转换,PIXELS_PER_METER为转换系数,这里设置为100    y1 /= PIXELS_PER_METER;    angle = angle*3.14 / 180;//convert t to radian    if (x1<0)    {        angle *= -1;    }    vx0 = x1*sqrt(g / 2 / (x1*tan(angle) - y1)); //求出初速度    vy0 = vx0 * tan(angle);    duration = x1 / vx0; //求出整个运动的时间    return_duration = duration; //将duration通过参数返回    pRet->initWithDuration(duration,startPosition, endPosition, angle,g, vx0, vy0);    pRet->autorelease();    return pRet;}bool Parabola::initWithDuration(float duration, const Point& startPosition, const Point& endPosition, float angle, float g, float vx0, float vy0){    if (CCActionInterval::initWithDuration(duration))    {        m_vx0 = vx0;        m_vy0 = vy0;        m_startPosition = startPosition;        m_endPosition = endPosition;        angle = angle*3.14 / 180;//convert t to radian        m_angle = angle;        m_dur = duration;        m_tan_a = tan(angle);        m_g = g;        return true;    }    return false;}Parabola* Parabola::clone() const{    CC_ASSERT(0);    return nullptr;}Parabola* Parabola::reverse() const{    CC_ASSERT(0);    return nullptr;}void Parabola::update(float time){    if (_target)    {        float elapsed = _elapsed; //获得当前的运动时间        float diff_x = m_vx0 * elapsed;        float diff_y = m_vy0 * elapsed - 0.5 * m_g * elapsed * elapsed;         CCPoint newPos = ccpAdd(m_startPosition, ccp(diff_x * PIXELS_PER_METER, diff_y * PIXELS_PER_METER)); //单位由米转换为像素        _target->setPosition(newPos);    }}

 

cocos3 抛物线运动