2013년 6월 16일 일요일

SidescrollControl.js

// SidescrollControl creates a 2D control scheme where the left
// pad is used to move the character, and the right pad is used
// to make the character jump.
//////////////////////////////////////////////////////////////

#pragma strict

@script RequireComponent( CharacterController ) //캐릭터 콘트롤러를 쓰겠다.

// This script must be attached to a GameObject that has a CharacterController
var moveTouchPad : Joystick; // 조이스틱 스크립트를 담는다. gui 텍스쳐 포함
var jumpTouchPad : Joystick;

var forwardSpeed : float = 4;  // 우측
var backwardSpeed : float = 4;  // 좌측
var jumpSpeed : float = 16;  // 점프 
var inAirMultiplier : float = 0.25; // 공중 에서... // Limiter for ground speed while jumping

private var thisTransform : Transform;  // 트랜스폼을 변수에 담기 위해..
private var character : CharacterController; 
private var velocity : Vector3; // Used for continuing momentum while in air
private var canJump = true; // 점프 가능한지

function Start()
{
// Cache component lookup at startup instead of doing this every frame
thisTransform = GetComponent( Transform );  // 트랜스폼을 담는다.
character = GetComponent( CharacterController );  // 캐릭터 콘트롤러를 담는다.

// Move the character to the correct start position in the level, if one exists
var spawn = GameObject.Find( "PlayerSpawn" );  // 플래이어 되살아나는 지점?
if ( spawn )
thisTransform.position = spawn.transform.position;  // 뭘까?
}

function OnEndGame()
{
// Disable joystick when the game ends
moveTouchPad.Disable(); // 사라지는 모양...죽으면..
jumpTouchPad.Disable();

// Don't allow any more control changes when the game ends
this.enabled = false;   // 몰라..
}

function Update()
{
var movement = Vector3.zero;  // 현재 해당하는 백터

// Apply movement from move joystick
if ( moveTouchPad.position.x > 0 )
movement = Vector3.right * forwardSpeed * moveTouchPad.position.x;   // 좌우 움직임
else
movement = Vector3.right * backwardSpeed * moveTouchPad.position.x;

// Check for jump
if ( character.isGrounded )  // 땅에 닿으면 
{
var jump = false; 
var touchPad = jumpTouchPad;  // 점프 터치 패드에서 가져와야지.. 정보를 

if ( !touchPad.IsFingerDown() )  // 터치패드를 누르면..
canJump = true;  // 점프 가능

if ( canJump && touchPad.IsFingerDown() )  // 또누르면.. 점프 불가능
{
jump = true;
canJump = false;
}

if ( jump )  // 점프일때
{
// Apply the current movement to launch velocity
velocity = character.velocity;  // 캐릭터 컨트롤로의 벨로시티를 가져와서 
velocity.y = jumpSpeed;  // y값에 힘을 준다. 
}
}
else  // 땅에 닿지 않으면 
{
// Apply gravity to our velocity to diminish it over time
velocity.y += Physics.gravity.y * Time.deltaTime;  // 해당 값에 중력을 더해준다... 

// Adjust additional movement while in-air  - 좌우로 좀 건드린다. 
movement.x *= inAirMultiplier; 
// movement.z *= inAirMultiplier;
}

movement += velocity;
movement += Physics.gravity;
movement *= Time.deltaTime;

// Actually move the character
character.Move( movement );

if ( character.isGrounded )
// Remove any persistent velocity after landing
velocity = Vector3.zero;
}

2013년 6월 12일 수요일

hp bar(2/2) - 그림 붙이기







아래는 게임에 사용될 바 이미지 입니다.
위에 것은
barTexture.png 이고 아래 것은 bgbarTexture.png 입니다.





-----------------------------------------------------
using UnityEngine;

using System.Collections;

public class ywplayerbar : MonoBehaviour {
public float maxBar = 100.0f;
public float justBar = 100.0f;

public Texture2D barTexture;
public Texture2D bgbarTexture;

public float barLength;

float bgjustBar = 100.0f;
float bgbarLength;
//float bgbarheight;

// Use this for initialization
void Start () {
barLength = Screen.width /2; // 바의 유니티 상 크기
bgbarLength = Screen.width /2; // 바 외곽의 유니티상...
}

// Update is called once per frame
void Update () {
AddjustCurrentBar(-3); // 1초에 얼마씩 줄일 것인지....

}

void OnGUI(){
//simplemode = 세가지 제공.. 그중 아래는 사간 화면 꽉 제운것...  true = 알파 브랜딩 오케이
GUI.DrawTexture(new Rect(13,10, barLength, 30), barTexture, ScaleMode.StretchToFill, true, 0.0F);
GUI.DrawTexture(new Rect(10,10, bgbarLength, 30), bgbarTexture, ScaleMode.StretchToFill, true, 0.0F);


// 박스로 작업한것에서.... 위에 드로우 텍스쳐로 바꾼 것은... 그림이 맘대로 제어되지 않았기 때문입니다.
//GUI.Box(new Rect(10,10,bgbarLength,20),bgbarTexture);
//GUI.Box(new Rect(10,10,barLength,20),barTexture);

}

public void AddjustCurrentBar(float adj){

justBar += adj * Time.deltaTime; // 1초에 얼마씩 줄일것인지.... 하는 변수

if(justBar<0) // 현재가 0보다 작으면...
justBar =0;
if(justBar>maxBar) // 현재가 맥스보다 크면..
justBar=maxBar; // 둘은 동일...
if(maxBar<1) // 맥스가 1보다 작으면...
maxBar=1;


barLength = (Screen.width/2)*(justBar/(float)maxBar);
// 빠지는 수치만큼 줄여나간다...
// 원래 크기에서...

}


}


생각보다 어려웟다는... 별다른 자료도 없고...
도데체 박스로 만들어 놓거나...

갭슐만 만든 예제는 결국 더 고민하게 만든다는...




hp bar(1/2) - 기본

using UnityEngine;
using System.Collections;

public class ywplayerbar : MonoBehaviour {
public float maxBar = 100.0f;
public float justBar = 100.0f;
public float bgjustBar = 100.0f;
public float barLength;
public float bgbarLength;

// Use this for initialization
void Start () {
barLength = Screen.width /2;
bgbarLength = Screen.width /2;
}

// Update is called once per frame
void Update () {
AddjustCurrentBar(-3);

}

void OnGUI(){

GUI.Box(new Rect(10,10,barLength,20),justBar + "/"+ maxBar);
GUI.Box(new Rect(10,10,bgbarLength,20),bgjustBar + "/"+ maxBar);
}

public void AddjustCurrentBar(float adj){

justBar += adj * Time.deltaTime;

if(justBar<0)
justBar =0;
if(justBar>maxBar)
justBar=maxBar;
if(maxBar<1)
maxBar=1;


barLength = (Screen.width/2)*(justBar/(float)maxBar);


}


}

unity3d 중요 팁

1) 백 버튼... 처리

if(Input.GetKeyDown(KeyCode.Escape)){ // 백버튼이 눌리면


}


2) 시간 경과 처리
var gameLength : float; // 제한 시간 길이
private var elapsed : float =0; // 체크 시간

elapsed += Time.deltaTime; // 체크 시간에 시간을 더한다. 제한시간보다 커지면 씬 전환..
if(elapsed >=gameLength){

GameController.SendMessage("PlayScene",1);
}

3) 터치하면

if(Input.touches.Length>0){

GameController.SendMessage("PlayScene",2);


}


4) 오브젝트 간에 이동을 동일하게...
var player : GameObject; // 플레이어를 담고
var pixcamera : float; // 카메라 영점을 맞춘다..

스타트 함수나... 업데이트 함수에..
var playerposition = player.transform; // 플레이어 트랜스폼을
var move = playerposition.position.y + pixcamera; // 픽스카메라 만큼 위치를 보정

transform.position.y = move;  // 카메라와 캐릭터는 이제 같이 움직인다.


5) 효과
1. 안개
   Edit/ Renderer Setting/ Fog
   
2. 바람 설정
GameObject>Create Other> WindZone

3. 눈
 Standard Assets/Particles/ Misc/Light Snow


6) 플랫폼 체크 //안드로이드면?

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        if (Application.platform == RuntimePlatform.Android)
            Debug.Log("Do something special here!");
        
    }
}










smoothfollow2d

using UnityEngine;
using System.Collections;

public class smoothfollow2d : MonoBehaviour {

public Transform target; 따라갈 타겟을 정한다.
public float petX; // 펫이 위치할 x값
public float petY;

private Transform thisTransform; // 자신의 트랜스폼을 담을 변수.
        public float smoothTime = 0.3F;  // 따라가는 속도
        private float Velocity = 0.0F; //평균 속도?
// Use this for initialization
void Start () {



thisTransform = transform; // 변수에 담아 퍼포먼스에 영향을 최소화
}

// Update is called once per frame
void Update () {


float newPositionX = Mathf.SmoothDamp(thisTransform.position.x, target.position.x+petX, ref Velocity, smoothTime);
float newPositionY = Mathf.SmoothDamp(thisTransform.position.y, target.position.y+petY, ref Velocity, smoothTime);
       
        thisTransform.position = new Vector3(newPositionX, newPositionY, thisTransform.position.z);



}
}

캐릭터 컨트롤러를 통한 이동... (2d 화면뷰에서는 사용할수 없다.)

using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]

public class cube : MonoBehaviour {
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;


    void Update() {
        CharacterController controller = GetComponent<CharacterController>(); // 캐릭터 콘트롤러 참조
        if (controller.isGrounded) { // 땅에 있으면
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); // 전후좌우 조정
            moveDirection = transform.TransformDirection(moveDirection); .. 축을 바꾼다. 월드 좌표로
            moveDirection *= speed;  // 움직임의 속도를 제어...
            if (Input.GetButton("Jump")) // 점프 버튼 누르면

                moveDirection.y = jumpSpeed;  // 해당 y값에 대입... 점프 한다.
           
        }
        moveDirection.y -= gravity * Time.deltaTime;  // y값에 조절 중력 가속도라고 보면 된다.
        controller.Move(moveDirection * Time.deltaTime);  // 콘트롤러는 이 모든 데이터를 참조하여 움직인다.. 시간 개념으로..
    }
}

캐릭터 콘트롤러...
이걸로 2D로 사용하려고 바보같은 짓을 했다..
일단 이건.. 중력값을 가지고 시작하는 것...

기본적으로 바닥이 있다는 전제하에 움직인다...
삽질 끝...

이런 간단한것들이... 괴롭힌다..

2013년 6월 11일 화요일

게임 제어 -


public enum GameState { playing, gameover }; // 게임 스테이트

public class GameControl : MonoBehaviour {

    public Transform platformPrefab; // 판떼기.. 이거 앞으로 막 쓸거.. 과일도 이것으로
    public static GameState gameState; // 현재 게임 상태

    private Transform playerTrans;  // 특정 트랜스 폼을 담기 위한 변수
    private float platformsSpawnedUpTo = 0.0f; // 얼마나 위에서 나타날 것인가?
    private ArrayList platforms; // 플랫폼 배열
    private float nextPlatformCheck = 0.0f;  // 담에 어디서 나타날 것인가?

 
void Awake () {
        playerTrans = GameObject.FindGameObjectWithTag("Player").transform; // 플레이어의 트랜스 폼을 찾는다.
        platforms = new ArrayList(); // 배열을 참조하고..

        SpawnPlatforms(25.0f);
        StartGame(); // 게임 시작


}

    void StartGame()
    {
        Time.timeScale = 1.0f;  // 게임진행
        gameState = GameState.playing; // 게임변수 변화
    }

    void GameOver()
    {
        Time.timeScale = 0.0f; //Pause the game
        gameState = GameState.gameover;
        GameGUI.SP.CheckHighscore();// 점수를 체크
    }

void Update () {
        //Do we need to spawn new platforms yet? (we do this every X meters we climb)
        float playerHeight = playerTrans.position.y;// 플레이어 의 위치를 참조...
        if (playerHeight > nextPlatformCheck)
        {
            PlatformMaintenaince(); //Spawn new platforms
        }

        //Update camera position if the player has climbed and if the player is too low: Set gameover.
        float currentCameraHeight = transform.position.y; // 카메라에 스크립트 붙어 있음... 카메라 위치를 참조
        float newHeight = Mathf.Lerp(currentCameraHeight, playerHeight, Time.deltaTime * 10);
        if (playerTrans.position.y > currentCameraHeight)
        {
            transform.position = new Vector3(transform.position.x, newHeight, transform.position.z); // 카메라 위치.
        }else{
            //Player is lower..maybe below the cameras view?
            if (playerHeight < (currentCameraHeight - 10))// 카메라와 캐릭터의 위치가 멀어지면 게임오바..
            {
                GameOver();
            }
        }

        //Have we reached a new score yet?
        if (playerHeight > GameGUI.score)
        {
            GameGUI.score = (int)playerHeight;
        }
}



    void PlatformMaintenaince()
    {
        nextPlatformCheck = playerTrans.position.y + 10;

        //Delete all platforms below us (save performance)
        for(int i = platforms.Count-1;i>=0;i--)
        {
            Transform plat = (Transform)platforms[i];
            if (plat.position.y < (transform.position.y - 10))
            {
                Destroy(plat.gameObject);
                platforms.RemoveAt(i);
            }          
        }

        //Spawn new platforms, 25 units in advance
        SpawnPlatforms(nextPlatformCheck + 25);
    }


    void SpawnPlatforms(float upTo) // 플랫폼 생성 같은데..
    {
        float spawnHeight = platformsSpawnedUpTo; 이 변수를 참조하고
        while (spawnHeight <= upTo) //작거나 같으면
        {
            float x = Random.Range(-10.0f, 10.0f); // 생성될 플랫폼의 x 위치를 랜덤하게 추출하고
            Vector3 pos = new Vector3(x, spawnHeight, 12.0f); // x위치 받고 높이 받고 z값은 생각좀 해봐야 함...

            Transform plat = (Transform)Instantiate(platformPrefab, pos, Quaternion.identity);  // plat 변수에.. 플랫폼 프리팹을 ,위치를 담고.. 생성?
            platforms.Add(plat); 배열에 집어 넣네?

            spawnHeight += Random.Range(1.6f, 3.5f); // 높이 값으로 체크 다음번 생성... 안에 있는 수치만큼 랜덤 y값을 더해서...
        }
        platformsSpawnedUpTo = upTo; // 다시 새 위치를 받는다.
    }

}