Draw a Line Sprite Between Two Points made by Sprites in Cocos2d

前端 未结 3 1740
不知归路
不知归路 2021-01-25 06:35

I\'ve been trying to draw a sprite line between 2 points made by sprites with mouse events on Xcode.

I have been following the steps given on a forum in this link: cocos

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 06:48

    I've not run the code but it looks fairly straightforward. The cause of the problem lies in this section:

    float dist = ccpDistance(lastTouchPoint, location);
    CCSprite *line = [CCSprite spriteWithFile:@"line.png"];
    [line setAnchorPoint:ccp(0.0f, 0.5f)];
    [line setPosition:lastTouchPoint];
    [line setScaleX:dist];
    

    This code calculates the distance between the two touch points in points (pixels), creates a new sprite (that will become the line) and sets the anchor point to the right hand side, centred vertically. It positions this at the point of the last touch and then sets the scale of the sprite's width based on the distance calculated earlier. This scaling factor will ensure the sprite is 'long' enough to reach between the two points.

    Your issue:

    This isn't taking into account the initial dimensions of the image you are loading (line.png). If this isn't a 1x1 dimension png then the setScale is going to make the resulting sprite too large - the overrun you are experiencing.

    The Solution

    Make line.png a 1 x 1 pixel image. Your code will work perfectly, though you will have a very thin line that is not aesthetically pleasing.

    Or, for best results, calculate the scale for the sprite by taking into account the width of line.png. This way the sprite can be more detailed and won't overrun.

    Change thesetScaleX line to this:

    [line setScaleX:dist / line.boundingBox.size.width];
    

提交回复
热议问题