스크롤뷰 추가하기



h++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef test370_hpp
#define test370_hpp
 
#include "cocos2d.h"
#include "cocos-ext.h"
 
USING_NS_CC;
USING_NS_CC_EXT;
 
 
class Test370 : public Layer
{
 
public:
    virtual bool init();
    static Scene* createScene();
    CREATE_FUNC(Test370);
};
 
#endif
cs



c++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "test370.hpp"
 
 
USING_NS_CC;
 
 
Scene* Test370::createScene()
{
    auto scene = Scene::create();
    
    auto layer = Test370::create();
    scene->addChild(layer);
    
    
    return scene;
}
 
 
bool Test370::init()
{
    if ( !Layer::init())
    {
        return false;
    }
    
    
    auto layer = LayerColor::create(Color4B(255,255,255,255));  //흰색의 레이어 생성
    layer->setContentSize(Size(100600));  //100x600 크기로 레이어 설정
    
    
    //100x320 크기의 스크롤뷰를 layer 컨테이너에 추가
    auto scroll = ScrollView::create(Size(100320), layer);
    //스크롤 방향 설정
    scroll->setDirection(ScrollView::Direction::VERTICAL);
    //스크롤 바운스 효과
    scroll->setBounceable(true);
    
    
    //스프라이트 이미지를 생성하여 스크롤안의 레이어에 추가
    auto sprite = Sprite::create("HelloWorld.png");
    sprite->setPosition(Point(50450));
    sprite->setScale(0.2);
    layer->addChild(sprite);
 
    
    //스크롤을 추가
    this->addChild(scroll);
 
    
    //스크롤안의 레이어의 위치를 280만큼 내려서 위에있는 이미지가 아래로 이동됨
    scroll->setContentOffsetInDuration(Point(0-280), 0.5);
    
    
    return true;
}
 
cs



결과)

왼쪽에 스크롤뷰가 생성된다

'IT > - 프로그래밍' 카테고리의 다른 글

안드로이드 ANT 설치  (0) 2017.03.26
Cocos Scale9Sprite 사용하기  (0) 2017.03.26
Cocos 효과음 출력하기  (0) 2017.03.23
Cocos 배경음악 출력하기  (0) 2017.03.22
Cocos 기본 파티클  (0) 2017.03.21

효과음 출력하기

배경음악은 1개만 출력되나 효과음은 여러개 출력될 수 있다



헤더파일과 네임스페이스

1
2
3
#include "SimpleAudioEngine.h"
 
using namespace CocosDenshion;
cs


효과음 출력

1
2
//playEffect(파일명, 반복여부) , 고유ID값 반환
int soundID = SimpleAudioEngine::getInstance()->playEffect("effect1.wav");
cs


효과음 미리로드

1
SimpleAudioEngine::getInstance()->preloadEffect("effect1.wav");
cs


효과음 일시정지

1
2
3
4
5
//pauseEffect(고유ID) : 해당 효과음 일시정지
SimpleAudioEngine::getInstance()->pauseEffect(soundID);
 
//모든 효과음 일시정지
SimpleAudioEngine::getInstance()->pauseAllEffects();
cs


효과음 재개

1
2
3
4
5
6
//resumeEffect(고유ID) : 해당 효과음 재개
SimpleAudioEngine::getInstance()->resumeEffect(soundID);
    
//모든 효과음 재개
SimpleAudioEngine::getInstance()->resumeAllEffects();
 
cs


효과음 중지

1
2
3
4
5
//stopEffect(고유ID) : 해당 효과음 중지
SimpleAudioEngine::getInstance()->stopEffect(soundID);
    
//모든 효과음 중지
SimpleAudioEngine::getInstance()->stopAllEffects();
cs


효과음 소리크기 지정

1
2
//범위 : 0~1
SimpleAudioEngine::getInstance()->setEffectsVolume(0.5);
cs


효과음 소리크기 반환

1
2
//범위 : 0~1
float volume = SimpleAudioEngine::getInstance()->getEffectsVolume();
cs


'IT > - 프로그래밍' 카테고리의 다른 글

Cocos Scale9Sprite 사용하기  (0) 2017.03.26
Cocos 스크롤뷰 추가하기  (0) 2017.03.24
Cocos 배경음악 출력하기  (0) 2017.03.22
Cocos 기본 파티클  (0) 2017.03.21
Cocos UserDefault 저장소  (0) 2017.03.20

배경음악 출력하기



헤더파일과 네임스페이스

1
2
3
#include "SimpleAudioEngine.h"
 
using namespace CocosDenshion;
cs


배경음악 출력

1
2
//playBackgroundMusic(파일명, 반복여부)
SimpleAudioEngine::getInstance()->playBackgroundMusic("background.mp3");
cs


배경음악 미리 로드

1
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("background.mp3");
cs


배경음악 일시정지

1
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
cs


배경음악 다시 재생 (일시정지된 배경음악을 다시 재생)

1
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
cs


배경음악 중지

1
2
//stopBackgroundMusic(메모리풀에서 해제여부)
SimpleAudioEngine::getInstance()->stopBackgroundMusic();
cs


배경음악 출력여부 확인

1
bool isPlay = SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying();
cs


배경음악 소리크기 지정

1
2
3
//범위 : 0~1
SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.5);
 
cs


배경음악 소리크기 반환

1
2
//범위 : 0~1
float volume = SimpleAudioEngine::getInstance()->getBackgroundMusicVolume();
cs


'IT > - 프로그래밍' 카테고리의 다른 글

Cocos 스크롤뷰 추가하기  (0) 2017.03.24
Cocos 효과음 출력하기  (0) 2017.03.23
Cocos 기본 파티클  (0) 2017.03.21
Cocos UserDefault 저장소  (0) 2017.03.20
Cocos Vector 사용  (0) 2017.03.19
기본 파티클


파티클 : 입자가 되는 작은 이미지를 가지고 다양한 효과를 연출하는 3D 애니메이션 기법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    auto particle1 = ParticleExplosion::create();   //폭발
    auto particle2 = ParticleFire::create();        //불모양
    auto particle3 = ParticleFireworks::create();   //불꽃모양
    auto particle4 = ParticleFlower::create();      //꽃모양
    auto particle5 = ParticleGalaxy::create();      //은하수모양
    
    auto particle6 = ParticleMeteor::create();      //유성모양
    auto particle7 = ParticleRain::create();        //비내리는모양
    auto particle8 = ParticleSmoke::create();       //연기모양
    auto particle9 = ParticleSnow::create();        //눈내리는모양
    auto particle10 = ParticleSpiral::create();     //나선모양
    
    auto particle11 = ParticleSun::create();        //해모양
    
    
    this->addChild(particle1);
cs


'IT > - 프로그래밍' 카테고리의 다른 글

Cocos 효과음 출력하기  (0) 2017.03.23
Cocos 배경음악 출력하기  (0) 2017.03.22
Cocos UserDefault 저장소  (0) 2017.03.20
Cocos Vector 사용  (0) 2017.03.19
안드로이드 나의 위치로 구글맵 띄우기  (1) 2017.03.18

UserDefault 저장소



UserDefault::getInstance() -> setBoolForKey(key , value) 

UserDefault::getInstance() -> setDoubleForKey(key , value)

UserDefault::getInstance() -> setFloatForKey(key , value)

UserDefault::getInstance() -> setIntegerForKey(key , value)

UserDefault::getInstance() -> setStringForKey(key , value)


UserDefault::getInstance() -> getBoolForKey(key)

UserDefault::getInstance() -> getDoubleForKey(key)

UserDefault::getInstance() -> getFloatForKey(key)

UserDefault::getInstance() -> getIntegerForKey(key)

UserDefault::getInstance() -> getStringForKey(key)




저장소에 저장

1
2
3
int highscore = UserDefault::getInstance()->getIntegerForKey("HIGHSCORE")+1;
UserDefault::getInstance()->setIntegerForKey("HIGHSCORE", highscore);
UserDefault::getInstance()->flush();
cs


저장소에서 불러오기

1
int highscore = UserDefault::getInstance()->getIntegerForKey("HIGHSCORE"0);
cs


Vector 사용



Vector 선언

1
Vector<Sprite*> smiles; 
cs


Vector 추가

1
2
3
auto sprite = Sprite::create("Pea.png");    
//스프라이트 객체를 vector에 추가
smiles.pushBack(sprite);
cs


Vector 요소 삭제

1
2
3
4
5
6
7
8
9
    for(Sprite *sprite : smiles){
        Rect rect = sprite->getBoundingBox();
        if(rect.containsPoint(location)){
            this->removeChild(sprite);
            smiles.eraseObject(sprite);
 
            break;
        }
    }
cs


Vector 크기

1
smiles.size()
cs


Vector 전체 삭제

1
smiles.clear();
cs


나의 위치로 구글맵 띄우기

GPS 를 이용하여 나의 위치찾기 -> 구글맵 띄우기



java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package com.ghj.ex_004;
 
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
 
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
 
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
 
    //GoogleMap 객체
    GoogleMap googleMap;
    MapFragment mapFragment;
    LocationManager locationManager;
    RelativeLayout boxMap;
    //나의 위도 경도 고도
    double mLatitude;  //위도
    double mLongitude; //경도
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        boxMap = (RelativeLayout)findViewById(R.id.boxMap);
 
        //LocationManager
        locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
 
 
        //GPS가 켜져있는지 체크
        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            //GPS 설정화면으로 이동
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            startActivity(intent);
            finish();
        }
 
        //마시멜로 이상이면 권한 요청하기
        if(Build.VERSION.SDK_INT >= 23){
            //권한이 없는 경우
            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(MainActivity.thisnew String[]{Manifest.permission.ACCESS_COARSE_LOCATION , Manifest.permission.ACCESS_FINE_LOCATION} , 1);
            }
            //권한이 있는 경우
            else{
                requestMyLocation();
            }
        }
        //마시멜로 아래
        else{
            requestMyLocation();
        }
    }
 
    //권한 요청후 응답 콜백
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //ACCESS_COARSE_LOCATION 권한
        if(requestCode==1){
            //권한받음
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                requestMyLocation();
            }
            //권한못받음
            else{
                Toast.makeText(this"권한없음", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
 
    //나의 위치 요청
    public void requestMyLocation(){
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            return;
        }
        //요청
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10010, locationListener);
    }
 
    //위치정보 구하기 리스너
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                return;
            }
            //나의 위치를 한번만 가져오기 위해
            locationManager.removeUpdates(locationListener);
 
            //위도 경도
            mLatitude = location.getLatitude();   //위도
            mLongitude = location.getLongitude(); //경도
 
            //맵생성
            SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
            //콜백클래스 설정
            mapFragment.getMapAsync(MainActivity.this);
        }
 
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("gps""onStatusChanged"); }
 
        @Override
        public void onProviderEnabled(String provider) { }
 
        @Override
        public void onProviderDisabled(String provider) { }
    };
 
    //구글맵 생성 콜백
    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;
 
        //지도타입 - 일반
        this.googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
 
        //나의 위치 설정
        LatLng position = new LatLng(mLatitude , mLongitude);
 
        //화면중앙의 위치와 카메라 줌비율
        this.googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
 
        //지도 보여주기
        boxMap.setVisibility(View.VISIBLE);
    }
}
cs



xml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
 
    <RelativeLayout
        android:id="@+id/boxMap"
        android:visibility="invisible"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <fragment
            android:id="@+id/map"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:name="com.google.android.gms.maps.SupportMapFragment"/>
    </RelativeLayout>
 
</LinearLayout>
cs



AndroidManifest.xml)

1
2
3
4
5
<!-- Google Map -->
<meta-data android:name="com.google.android.geo.API_KEY" android:value="" />
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
cs



gradle)

1
2
3
4
dependencies {
    ...
    compile 'com.google.android.gms:play-services-maps:9.8.0'
}

cs


문제)

Unable to connect to adb. Check if adb is installed correctly.



해결)

<SDK 경로>\platform-tools\adb 를 복사하여 uiautomatorviewer가 있는 <SDK 경로>\tools\bin 에 붙여넣는다



결과)


타일이미지를 이용한 배경스크롤 하기



h++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef test260_hpp
#define test260_hpp
 
#include "cocos2d.h"
 
USING_NS_CC;
 
class Test260 : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();
    
    virtual bool init();
    
    // implement the "static create()" method manually
    CREATE_FUNC(Test260);
    
    
    void initBG();   //배경
};
 
#endif
cs



c++)

타일이미지를 반복 추가하여 배경이미지를 만들고 타일이미지 만큼 스크롤한다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "test260.hpp"
 
USING_NS_CC;
 
Scene* Test260::createScene()
{
    auto scene = Scene::create();
    
    auto layer = Test260::create();
    scene->addChild(layer);
    
    
    return scene;
}
 
 
bool Test260::init()
{
    if ( !Layer::init())
    {
        return false;
    }
    
    
    initBG();
    
    return true;
}
 
 
//배경그리기
void Test260::initBG(){
    //배경레이어
    auto bgLayer = Layer::create();
    this->addChild(bgLayer);
    
    //이미지를 반복하여 추가한다 (가로8개 세로6개)
    for(int i=0; i<8; i++){
        for(int j=0; j<6; j++){ //이미지 끊김 현상을 없애기 위해 타일이미지 1개를 더 추가한다
            auto sprite = Sprite::create("tile.png");
            sprite->setAnchorPoint(Point::ZERO);
            sprite->setPosition(Point(i*72 , j*72));
            bgLayer->addChild(sprite);
        }
    }
    
    //배경레이어에 애니메이션 적용
    //전체화면이 아닌 타일이미지 만큼만 스크롤한다
    auto action1 = MoveBy::create(2.0, Point(0,-72));
    auto action2 = Place::create(Point::ZERO);
    auto action3 = Sequence::create(action1, action2, NULL);
    auto action4 = RepeatForever::create(action3);
    bgLayer->runAction(action4);
}
 
 
cs



결과

아래방향으로 스크롤 된다



ParallaxNode를 이용한 배경스크롤 구현하기



h++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef test257_hpp
#define test257_hpp
 
#include "cocos2d.h"
 
USING_NS_CC;
 
class Test257 : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();
    
    virtual bool init();
    
    // implement the "static create()" method manually
    CREATE_FUNC(Test257);
    
    
    void initBG();   //배경
};
 
#endif 
cs



c++)

배경레이어 대신 ParallaxNode를 생성하고 스프라이트 객체를 ParallaxNode에 추가한다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "test257.hpp"
 
USING_NS_CC;
 
Scene* Test257::createScene()
{
    auto scene = Scene::create();
    
    auto layer = Test257::create();
    scene->addChild(layer);
    
    
    return scene;
}
 
 
bool Test257::init()
{
    if ( !Layer::init())
    {
        return false;
    }
    
    
    initBG();
    
    return true;
}
 
 
//배경그리기
void Test257::initBG(){
    //배경레이어 대신 ParallaxNode 에 액션기능을 구현하고 스프라이트 객체를 ParallaxNode 에 추가
    auto node = ParallaxNode::create();
    this->addChild(node);
    
    //ParallaxNode 에 애니메이션 구현
    auto action1 = MoveBy::create(10.0, Point(-2000,0));
    auto action2 = Place::create(Point::ZERO);
    auto action3 = Sequence::create(action1, action2, NULL);
    auto action4 = RepeatForever::create(action3);
    node->runAction(action4);
    
    /** 첫번째 이미지 **/
    auto sprite1 = Sprite::create("background2.png");
    sprite1->setAnchorPoint(Point::ZERO);
    //addChild(스프라이트, z-order, 이동비율, 좌표) : ParallaxNode 에 Sprite 객체 추가
    //이동비율 : ParallaxNode를 기준으로 한 이동비율
    //         1이면 ParallaxNode와 똑같이 이동하고 0이면 이동하지 않으며 2이면 ParallaxNode보다 2배 빨리 이동한다
    node->addChild(sprite1, 0, Point(1,0), Point::ZERO);
    
    auto sprite2 = Sprite::create("background2.png", Rect(0,0,480,320));
    sprite2->setAnchorPoint(Point::ZERO);
    node->addChild(sprite2, 0, Point(1,0), Point(2000,0));
    
 
    /** 두번째 이미지 **/
    auto sprite3 = Sprite::create("background3.png");
    sprite3->setAnchorPoint(Point::ZERO);
    node->addChild(sprite3, 1, Point(2,0), Point::ZERO);
    
    //같은시간에 ParallaxNode 보다 2000px 더 이동하므로 스프라이트 객체를 1개더 추가한다
    auto sprite4 = Sprite::create("background3.png");
    sprite4->setAnchorPoint(Point::ZERO);
    node->addChild(sprite4, 1, Point(2,0), Point(2000,0));
    
    auto sprite5 = Sprite::create("background3.png", Rect(00480114));
    sprite5->setAnchorPoint(Point::ZERO);
    node->addChild(sprite5, 1, Point(2,0), Point(4000,0));
}
 
 
cs




+ Recent posts