Cocos2d:使用 CCCamera 做滚动效果 (Four Ways of Scrolling with Cocos2D)

原文:http://www.koboldtouch.com/display/IDCAR/Four+Ways+of+Scrolling+with+Cocos2D

There are two classes of scrolling, "fake" and "real". Altogether there are four ways to create a scrolling view in Cocos2D: with CCCamera, with CCFollow, manually moving a layer and "faking it". I‘ll discuss each approach and show their advantages and disadvantages
as well as point out for which types of games they work best.

The example projects for this article can be downloaded from github.

Fake Scrolling - Merely creating the Illusion of Scrolling

Ideal for "endless scrolling" games. Typical genres include jumping or running games like Doodle Jump and Canabalt, as well as shoot‘em ups.

These games mainly scroll along one axis, often scrolling only in one direction. The other axis has a limited range or is not scrolled at all. The fake scrolling approach prevents the coordinates of game objects to "explode" to similarly infinite coordinate
points. This could introduce rounding errors in floating point values which may accumulate over time, causing inaccuracies at later stages of the game.

To create the illusion of scrolling, at least two background image sprites are needed. Four are needed if you also want to scroll a little along the minor scrolling axis. The background images must be repeating seamlessly, and each must be at least the size
of the screen. The trick is to use the two or four images and move them in the opposite direction of where the player is supposedly heading. This creates the illusion that the player is actually moving in a certain direction. Once one background image has
scrolled entirely outside the view, it will be repositioned by adding the width or height of the screen (depending on major scrolling axis) to the position of all background sprites. The player does not notice this repositioning, which allows the background
sprites to continue moving in the current direction seemingly endlessly.

Game objects (enemies, items, etc.) usually enter the screen from the side towards which the player is moving, but any location is possible. You would normally spawn these objects one screen ahead (or behind) what is currently visible, then move them on screen.
Movement of enemies can be fixed if the scrolling occurs at a constant rate and never stops. Otherwise all game object‘s positions must be updated with the delta scroll value every time to keep them fixed at their current position. You would do this at a central
location before or after moving the game objects. Without this, varying the scrolling speed would also speed up or slow down the movement of game objects, which is probably not what you want. This voids the use of CCMove* actions because they don‘t consider
external modification of the position property while they‘re running.

From a game construction perspective this type of scrolling lends itself well for randomly generated worlds. You can alway use a certain location in front of or behind the scrolling direction to spawn new game objects. You always have only a relatively short
list of game objects that are alive in this "world", so each object can be allowed to run relatively complex code. And you can dismiss game objects easily by checking if they have moved past the threshold location. All coordinates are relative to screen coordinates,
so at most you‘re dealing with a value range 3 times that the size or width of the screen (one screen ahead, one screen behind, and the actual screen - more if you allow scrolling along both axes).

Using object pooling you can reuse a predetermined amount of game objects of a certain type and thus also avoid spawning too many of the same type. For example if there can be 10 Zombies on the screen at once, you‘d create 10 Zombies up front, set them to inactive
and simply reposition and activate them to spawn one. When you have 10 Zombies on the screen and game logic dictates to spawn another one, you can‘t and no new Zombie gets spawned. This design lends itself well to high performance and has built-in limits that
avoid many (but not all) possibly unfair game situations that can occur in randomly generated worlds.

Code Example:

The scrolling effect is created by moving the background images. This example uses two images moving from right to left, to give the impression of movement from left to right. You can also put the background images into a separate layer and move them all at
once by adjusting the layer‘s position.

-(void)
update:(ccTime)delta

{

    CGPoint
bg1Pos = _bg1.position;

    CGPoint
bg2Pos = _bg2.position;

    bg1Pos.x
-= kScrollSpeed;

    bg2Pos.x
-= kScrollSpeed;

    

    //
move scrolling background back from left to right end to achieve "endless" scrolling

    if

(bg1Pos.x < -(_bg1.contentSize.width))

    {

        bg1Pos.x
+= _bg1.contentSize.width;

        bg2Pos.x
+= _bg2.contentSize.width;

    }

    

    //
remove any inaccuracies by assigning only int values (this prevents floating point rounding errors accumulating over time)

    bg1Pos.x
= (
int)bg1Pos.x;

    bg2Pos.x
= (
int)bg2Pos.x;

    _bg1.position
= bg1Pos;

    _bg2.position
= bg2Pos;

}

Use when:

  • Your game should scroll endlessly or very far.
  • Your game primarily scrolls along one axis, perhaps even in one direction. A "tube-like" world.
  • Your game randomly generates most or all of the world as the game progresses.

Avoid when:

  • Your game needs to scroll in any direction.
  • Your game uses a "designed" world (predetermined locations of objects, backgrounds, etc) of finite size.
  • Your game‘s background images do not repeat.

 All objects use relative screen coordinates,
easy to work with. No "explosion" of coordinate values in infinitely scrolling worlds.

 No conversion of touch coordinates necessary.

 Ideal for randomly generating content.

 The player character stays fixed or at least
only moves within screen coordinates or a a little more.

 Code complexity increases if direction
of scrolling can go both ways (ie right and left, or up and down) or allows scrolling at variable speed. CCMove* actions can not be used in these cases.

 Not suitable for two equally valid
scrolling directions (ie square worlds). Main scrolling direction is either vertical or horizontal, with the other axis either not scrolling at all or only within a small range.

 Adapting to various screen aspect ratios
(iPhone, iPhone widescreen, iPad) requires extra care.

"Real" Scrolling - Using the Screen as View onto the World

Ideal for larger worlds. The player can travel freely in all four directions at any speed. Typical examples include games where the player traverses large worlds, for example Zelda or Super Mario.

You can scroll a world either by using CCCamera or my adjusting the position of a parent node. The CCFollow method falls into the latter category. The main difference between CCCamera and CCFollow or layer movement is that CCCamera moves the viewport over the
fixed (non-moving) world whereas CCFollow or layer movement move the world underneath the fixed camera. The end result is the same.

Use when:

  • Your game should scroll equally in any direction.
  • Your game is a designed world, or randomly generated but has a finite size.
  • Your game world is a tilemap.

Avoid when:

  • Your game needs to scroll endlessly or very far (far = over ten thousands points in any direction).
  • Your game relies on randomly creating its world. Even if it needs to scroll in any direction fake scrolling may be a better solution.

Scrolling with CCCamera

CCCamera is a wrapper for the OpenGL gluLookAt function. It has the most flexibility allowing free rotating, zoom and even perspective views. But it‘s also more difficult to work with and not fully compatible with all aspects of cocos2d. CCMenu won‘t work,
and converting touch coordinates will be a challenge. The biggest problem of CCCamera is probably that there‘s a serious lack of expertise - there are many CCCamera related questions on the cocos2d forum and in other places, but hardly any good answers. Most
questions simply remain unanswered. CCCamera works differently than anything else in cocos2d, and affects cocos2d rendering in ways you may not understand or foresee. Therefore I strongly discourage anyone from using CCCamera unless that anyone is familiar
with OpenGL viewport basics, gluLookAt and transformation matrices (conversion of screen to view coordinates).

Even if you do know about these things, use CCCamera only when you need the full flexibility of a zooming, rotating or perspective camera view. For example if you want a driving game which should keep the car always facing up, rotating the world relative to
where the car is going, then you‘d have to use the CCCamera. Implementing this with layer movement will be more difficult and certainly requires a different approach to how the car movement is handled (the car would actually never rotate by itself, and would
always face in a fixed direction).

Code Example:

You first need to get all the camera values by reference (&centerX) in C programming language fashion. Then you need to update both center and eye to be at the same position in order to maintain an orthogonal (top down) view. Introducing 3D effects is as simple
as allowing center and eye to deviate. Then you must set all values back to the camera, including those you haven‘t modified to ensure you don‘t accidentally change one of the values you didn‘t modify.

For example, if you hard code the value 0.0 when setting centerZ and eyeZ, for some reason the screen goes black even though the values for centerZ and eyeZ returned from CCCamera are 0.0 as well. This is just one of the oddities of CCCamera.

-(void)
update:(ccTime)delta

{

    //
get the layer‘s CCCamera values

    float

centerX, centerY, centerZ;

    float

eyeX, eyeY, eyeZ;

    [self.camera
centerX:&centerX centerY:&centerY centerZ:&centerZ];

    [self.camera
eyeX:&eyeX eyeY:&eyeY eyeZ:&eyeZ];

    

    //
set camera center & eye to follow player position (centered on screen)

    centerX
= eyeX = (_player.position.x - _screenSize.width *
0.5f);

    centerY
= eyeY = (_player.position.y - _screenSize.height *
0.5f);

    

    //
Make sure not to scroll near the world boundaries, to prevent showing the area outside the world.

    //
Note: this code does not take into account zooming out or in by modifying the camera‘s eyeZ value.

    centerX
= eyeX = clampf(centerX,
0.0f,
_worldSize.width - _screenSize.width);

    centerY
= eyeY = clampf(centerY,
0.0f,
_worldSize.height - _screenSize.height);

    

    //
update the camera values

    [self.camera
setCenterX:centerX centerY:centerY centerZ:centerZ];

    [self.camera
setEyeX:eyeX eyeY:eyeY eyeZ:eyeZ];

}

Use when:

  • Your game needs a perspective view, or rotation animations, or elaborate zooming actions that would be difficult to implement with any of the other scrolling methods.

Avoid when:

  • Always, by default.
  • If you do not have an understanding (and don‘t want to learn about) gluLookAt, the OpenGL viewport, coordinate conversion.
  • If you want to use CCMenu in your in-game user interface.

 Scroll in any direction.

 CCCamera uses world coordinates.

 Also allows to zoom in/out of the world as
well as rotation and even perspective (3D) effects.

 CCCamera is not well documented or
tutorialized. It‘s also rarely used so it‘s hard to get (good) answers to CCCamera related questions. Many issues require a deeper understanding of OpenGL.

 CCCamera uses an awkward C-style interface
for getting and setting position and look at points.

 Touch coordinates must be converted
to world coordinates. Conversion is complex, involving camera coordinates and "magic numbers".

 Not fully compatible with all nodes.
For example CCMenu will not work correctly because it does not implement the necessary touch conversion.

 When zooming with CCCamera there is
a value range threshold where objects start to disappear. This threshold is different on different devices.

Scrolling with CCFollow

CCFollow works by changing the position of the node that is running the CCFollow action relative to the position of the followed node. Typically you‘ll run it on the layer that contains the node (usually the player-controlled object) to be followed.

CCFollow should only run on non-drawing nodes (CCNode, CCLayer, CCScene) and should follow a node that is one of its direct children. Especially if the followed node is not a direct children you might notice that the screen follows the object but it does so
at an offset.

CCFollow is the easiest way to create a scrolling view, but it‘s also the least flexible. You can choose between limitless scrolling, or scrolling that stops at predefined (world) boundaries. That is all. For everything else you‘ll have to subclass CCFollow
and add whatever code you need to improve the scrolling behavior.

Code Example:

CCFollow requires the least amount of code to implement scrolling. Just add this code in init or onEnter to allow the layer (self) to scroll so that the followed node (_player) is always centered on screen. Additionally this code enables the world boundaries
check so that scrolling stops before any part outside of the world becomes visible. The player is still able to move up to the world border, or even beyond that if you don‘t limit the player‘s movement as well.

//
Let the layer follow the player sprite, while restricting the scrolling to within the world size.

//
This is really all you need to do. But it‘s really all you *can* do either without modifying CCFollow‘s code.

CGRect
worldBoundary = CGRectMake(
0,
0,
_worldSize.width, _worldSize.height);

[self
runAction:[CCFollow actionWithTarget:_player worldBoundary:worldBoundary]];

Use when:

  • You need to get started quickly with a scrolling view.

Avoid when:

  • You need to influence any scrolling parameters, such as how closely the node is followed or how the scrolling accelerates and decelerates.

 Scroll in any direction.

 Always keeps the followed node centered.

 Allows to specify world boundaries to clamp
scrolling at world borders.

 No control whatsoever. Follow speed,
follow range, acceleration/deceleration of scrolling movement, prevent scrolling in a particular direction, and so on - none of that is supported.

 Changes position of the node running
the action. Typically that will be a layer, so it shouldn‘t matter.

 Touch coordinates must be converted
to world coordinates using built-in convertToWorldSpace.

 Implementing zoom in/out centered on
a particular object is difficult. Rotating relative to an object is very difficult.

Custom Scrolling by subclassing CCFollow

This is essentially the same method that CCFollow uses, but you will have to implement any additional behavior yourself. Typically you will want to subclass CCFollow because that‘ll be easier, but you can also rip out the guts of CCFollow and put the scrolling
code in your layer‘s update method. For example if you want the scrolling to happen only when the followed node is getting close enough to one of the screen borders, you‘d have to subclass CCFollow, override the step method, put the original code back in and
then start modifying how CCFollow updates the position. An example is given in the CCCustomFollow demo.

The main downside caused by moving an underlying layer is that the position of that layer is the inverse of the actual movement. For example to scroll 100 pixels to the right, you have to subtract 100 pixels from the layer‘s position, which then may have a
negative position of -100. You might find it counterintuitive that the targetPos CGPoint in CCFollow uses mostly negative coordinates - because to scroll to the right and up, the target node (usually the layer) must move in the opposite direction, to the left
and down.

Code Example:

First create a subclass of CCFollow, in this case I named it CCCustomFollow. Initialize it like CCFollow above, and override the step method in CCCustomFollow. You can start with the CCFollow code as basis, understand it first, then start modifying it.

This example prevents scrolling while the followed node is within 120 points of the center. Once the followed node crosses that distance, the scrolling will start following the followed node. This is a very simplified example of "border scrolling". You still
need to improve this in several ways, for example to ensure that the scrolling correctly stops at world boundaries and perhaps to improve it so that the non-scrolling area is not a circle but a rectangle. You might also attempt to scroll faster when the followed
node leaves the threshold so that the followed node becomes centered on the screen again. All of those tasks aren‘t exactly trivial, but they‘re manageable if you have a reasonably solid understanding of trigonometry.

-(void)
step:(ccTime) dt

{

    //
The targetPos coordinate values become more negative the more the followed node moved to the right and up.

    //
This is because the layer is moved in the opposite direction of where the followed node is heading.

    CGPoint
targetPos = ccpSub(halfScreenSize, followedNode_.position);

    targetPos.x
= clampf(targetPos.x, leftBoundary, rightBoundary);

    targetPos.y
= clampf(targetPos.y, bottomBoundary, topBoundary);

 

    //
initialize currentPos once

    if

(isCurrentPosValid == NO)

    {

        isCurrentPosValid
= YES;

        currentPos
= targetPos;

    }

    //
if current & target pos are this many points away, scrolling will start following the followed node

    const

float

kMaxDistanceFromCenter =
120.0f;

        

    float

distanceFromCurrentToTargetPos = ccpLength(ccpSub(targetPos, currentPos));

    if

(distanceFromCurrentToTargetPos > kMaxDistanceFromCenter)

    {

        //
get the delta movement to the last target position

        CGPoint
deltaPos = ccpSub(targetPos, previousTargetPos);

        //
add the delta to currentPos to track followed node at the distance threshold

        currentPos
= ccpAdd(currentPos, deltaPos);

        [target_
setPosition:currentPos];

    }

    previousTargetPos
= targetPos;

}

Use when:

  • You need full flexibility over the scrolling behavior.

Avoid when:

  • You need functionality only CCCamera can provide, such as rotation relative to followed node‘s movement direction.

 Scroll in any direction.

 More scrolling flexibility - if implemented.

 Do it yourself, but you can use the
CCFollow code as basis. Here‘s another good starting point but the code has "All Rights Reserved".

 May feel counter-intuitive, since position
of the node (layer) that causes the scrolling effect is the inverse of the actual scrolling direction.

 Touch coordinates must be converted
to world coordinates using built-in convertToWorldSpace.

 Implementing zoom in/out centered on
a particular object is difficult. Rotating relative to an object is very difficult.

时间: 2024-10-16 02:32:00

Cocos2d:使用 CCCamera 做滚动效果 (Four Ways of Scrolling with Cocos2D)的相关文章

ios:仿照安卓小米商城head左右滚动效果(多屏滚动)

1.之前做的应用需要这个效果但是当时用的比较复杂(绘图)的方法来实现,现在想到了一个新的方法. 2.用到了http://www.cnblogs.com/yoon/p/3616503.html 里面的小技巧 3.思路: 主要是在新的scrollview中重写Layoutsubviews 代码如下: - (void)layoutSubviews { [super layoutSubviews]; for (UIView *view in self.subviews) { if (view.tag =

全屏滚动效果H5FullscreenPage.js

前提: 介于现在很多活动都使用了 类似全屏滚动效果 尤其在微信里面 我自己开发了一个快速构建 此类项目的控件 与市面上大部分控件不同的是此控件还支持元素的动画效果 并提供多种元素效果 基于zepto.js 功能清单: 1 快速实现页面全屏滚动效果.并提供多种翻页效果,兼容大部分ios和android系统. 2 支持在页面中添加多种动画元素效果 来实现淡入,滑入等效果. 3 支持配置音乐功能. 4 支持摇一摇接口功能. 组件核心代码原理: 1 页面滚动 在移动页面上如果想使用滚动,如过没有任何动画

jquery实现的一个导航滚动效果

在做校园网视频网站的时候,首页有一个导航页面要实现滚动效果,有样例,但代码是在难弄懂,貌似网页设计这块还是只有自己的代码自己懂,索性就仿造别人的效果自己做了一个,大体上还行,看起来还是比较流畅的,不次于原作的幺. 现在先把代码拷贝到这里,以后再逐一简化修改: 实现混动效果,脚本代码如下: var all=0; //滚动单位的个数 var no=0; //当前要滚动的位置,每隔短时间递增 var s_width=0; //滚动单位的宽度 $(document).ready(function(){

JS实现鼠标移上去图片停止滚动移开恢复滚动效果

这是在做个人站的时候展示项目成果,因为不光需要展示,还需要介绍详细内容,就在滚动展示的地方做了这个效果以便于点开想要看的项目. 首先,要做的是一个需要滚动的区域.我前边写过一个关于图片循环滚动的示例,那个是一块块的的滚动==>实现图片的循环滚动 . 这次我们就做滚动区域是平滑循环滚动效果. 下边是布局的HTML代码,原理是在要展示区域的div(.ban_img)里加一个能包含所有需要展示的图的大div(.in_img), <div class=" ban_img">

jQuery实现滚动效果详解1

声明:第一次写原创,本人初学,很多地方一知半解,本篇算是一个学习的笔记,欢迎批评指正,转载请注明. 今天要做的效果是在网上经常能看到多幅图片向左无缝滚动,鼠标滑过动画暂停,鼠标滑出动画继续的效果.网上现成的代码和插件很多,拿来用有时候不大顺手,今天我就来学习一下它的原理. 要实现这个效果:1.需要一个展示区,滚动的内容只有通过展示区才能被看到id=visual_area2.把滚动的内容横向排列的载体,我们姑且叫它画布,注意不能理解PS中的画布class=scroll_area3.看起来要滚动的内

手机端触屏滚动效果

因为现在做的项目在手机上的,而使用 overflow: scroll;用自带的滚动效果在IOS的手机上很卡不知道什么原因,同事建议自己写一个这样的效果来解决,所以找了下资料自己弄了下目前效果还不知道这么样先贴上来备份一下不知道项目中要不要改!!! html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test&l

iOS 字体滚动效果 ScrollLabel

写了一个简单的字体滚动效果. 用了一种取巧的方式,传入两个一摸一样的Label(当然也可以是别的视图), 话不多说,代码里面讲解. SEScrollLabel.h #import <UIKit/UIKit.h> /*! @brief 回调代码块 * * 当滚动效果持续loopsDone次之后,isFinished值会变为YES,执行代码块 * @param loopsDone 滚动效果执行次数 * @param isFinished 是否已经结束 */ typedef void (^PMAni

iOS UIWebView 获取内容实际高度,关闭滚动效果

iOS UIWebView 获取内容实际高度,关闭滚动效果 近期做东西,将 UIWebView 嵌套在 UIScrollView 里,由 UISCrollView 控制滚动,需要使 UIWebView 的高度同内容高度一致,网上搜索的到代码: htmlHeight = [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]; 这段代码是无效的,body 获取到的 offsetHeigh

整屏滚动效果 jquery.funnPage.js插件+CSS3实现

最近很流行整屏滚动的效果,无论是在PC端还是移动端,本人也借机学习了一下,主要通过jquery.funnPage.js插件+CSS3实现效果. 本人做的效果: 首先使用要引入插件 <link rel="stylesheet" href="../c/jquery.fullPage.css" media="all"/> <script type="text/javascript" src="../j/l