Настройка FPC-камеры на Андроиде - Форум Игроделов
Пн, 20 Май 2024, 10:42 
 
Приветствую Вас Гость Главная | Регистрация | Вход
Новые сообщения · Участники · Правила форума · Поиск · RSS ]
  • Страница 1 из 1
  • 1
Форум Игроделов » UNITY3D » ОБЩИЕ ВОПРОСЫ » Настройка FPC-камеры на Андроиде
Настройка FPC-камеры на Андроиде
dostalitionДата: Пн, 21 Апр 2014, 02:59 | Сообщение # 1
 
Сообщений: 155
Награды: 0
Репутация: 9
Статус: Offline
Начал осваивать разработку под Андрюху и столкнулся с непоняткой в управлении ... Подскажите какие параметры потискать, чтобы изменить чувствительность и инерцию вращения камеры тачем ? Как-то Гугл не помог, может не те слова вбивал smile В инспекторе есть три параметра tilt, но , как их не крутил, ничего не изменилось, вроде бы ...

Добавлено (21 Апр 2014, 02:59)
---------------------------------------------
Есть кто живой ?

 
СообщениеНачал осваивать разработку под Андрюху и столкнулся с непоняткой в управлении ... Подскажите какие параметры потискать, чтобы изменить чувствительность и инерцию вращения камеры тачем ? Как-то Гугл не помог, может не те слова вбивал smile В инспекторе есть три параметра tilt, но , как их не крутил, ничего не изменилось, вроде бы ...

Добавлено (21 Апр 2014, 02:59)
---------------------------------------------
Есть кто живой ?


Автор - dostalition
Дата добавления - 21 Апр 2014 в 02:59
AltairДата: Пн, 21 Апр 2014, 12:08 | Сообщение # 2
Unity 3D PRO Developer
 
Сообщений: 758
Награды: 6
Репутация: 195
Статус: Offline
Цитата dostalition ()
чувствительность и инерцию вращения камеры тачем

плавность уменьшить и сделать слабее силу поворота и всё..в обще кинь скрипт поворота.
 
Сообщение
Цитата dostalition ()
чувствительность и инерцию вращения камеры тачем

плавность уменьшить и сделать слабее силу поворота и всё..в обще кинь скрипт поворота.

Автор - Altair
Дата добавления - 21 Апр 2014 в 12:08
dostalitionДата: Чт, 24 Апр 2014, 18:48 | Сообщение # 3
 
Сообщений: 155
Награды: 0
Репутация: 9
Статус: Offline
Ну, Я использую стандартный Фёст Персон Контрол из Станд.АссетсМобайл, и так понимаю, что этим делом управляет либо скрипт Joystick , либо FirstPersonControl ...
Код
#pragma strict

@script RequireComponent( GUITexture )

// A simple class for bounding how far the GUITexture will move
class Boundary  
{
  var min : Vector2 = Vector2.zero;
  var max : Vector2 = Vector2.zero;
}

static private var joysticks : Joystick[];     // A static collection of all joysticks
static private var enumeratedJoysticks : boolean = false;
static private var tapTimeDelta : float = 0.3;    // Time allowed between taps

var touchPad : boolean;          // Is this a TouchPad?
var touchZone : Rect;
var deadZone : Vector2 = Vector2.zero;      // Control when position is output
var normalize : boolean = false;        // Normalize output after the dead-zone?
var position : Vector2;          // [-1, 1] in x,y
var tapCount : int;                              // Current tap count

private var lastFingerId = -1;        // Finger last used for this joystick
private var tapTimeWindow : float;       // How much time there is left for a tap to occur
private var fingerDownPos : Vector2;
private var fingerDownTime : float;
private var firstDeltaTime : float = 0.5;

private var gui : GUITexture;        // Joystick graphic
private var defaultRect : Rect;        // Default position / extents of the joystick graphic
private var guiBoundary : Boundary = Boundary();   // Boundary for joystick graphic
private var guiTouchOffset : Vector2;      // Offset to apply to touch input
private var guiCenter : Vector2;       // Center of joystick

function Start()
{
  // Cache this component at startup instead of looking up every frame  
  gui = GetComponent( GUITexture );
   
  // Store the default rect for the gui, so we can snap back to it
  defaultRect = gui.pixelInset;  
      
     defaultRect.x += transform.position.x * Screen.width;// + gui.pixelInset.x; // -  Screen.width * 0.5;
     defaultRect.y += transform.position.y * Screen.height;// - Screen.height * 0.5;
      
     transform.position.x = 0.0;
     transform.position.y = 0.0;
          
  if ( touchPad )
  {
   // If a texture has been assigned, then use the rect ferom the gui as our touchZone
   if ( gui.texture )
    touchZone = defaultRect;
  }
  else
  {     
   // This is an offset for touch input to match with the top left
   // corner of the GUI
   guiTouchOffset.x = defaultRect.width * 0.5;
   guiTouchOffset.y = defaultRect.height * 0.5;
    
   // Cache the center of the GUI, since it doesn't change
   guiCenter.x = defaultRect.x + guiTouchOffset.x;
   guiCenter.y = defaultRect.y + guiTouchOffset.y;
    
   // Let's build the GUI boundary, so we can clamp joystick movement
   guiBoundary.min.x = defaultRect.x - guiTouchOffset.x;
   guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;
   guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;
   guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;
  }
}

function Disable()
{
  gameObject.SetActive(false);
  enumeratedJoysticks = false;
}

function ResetJoystick()
{
  // Release the finger control and set the joystick back to the default position
  gui.pixelInset = defaultRect;
  lastFingerId = -1;
  position = Vector2.zero;
  fingerDownPos = Vector2.zero;
   
  if ( touchPad )
   gui.color.a = 0.025;  
}

function IsFingerDown() : boolean
{
  return (lastFingerId != -1);
}
   
function LatchedFinger( fingerId : int )
{
  // If another joystick has latched this finger, then we must release it
  if ( lastFingerId == fingerId )
   ResetJoystick();
}

function Update()
{  
  if ( !enumeratedJoysticks )
  {
   // Collect all joysticks in the game, so we can relay finger latching messages
   joysticks = FindObjectsOfType( Joystick ) as Joystick[];
   enumeratedJoysticks = true;
  }  
    
  var count = Input.touchCount;
   
  // Adjust the tap time window while it still available
  if ( tapTimeWindow > 0 )
   tapTimeWindow -= Time.deltaTime;
  else
   tapCount = 0;
   
  if ( count == 0 )
   ResetJoystick();
  else
  {
   for(var i : int = 0;i < count; i++)
   {
    var touch : Touch = Input.GetTouch(i);    
    var guiTouchPos : Vector2 = touch.position - guiTouchOffset;
   
    var shouldLatchFinger = false;
    if ( touchPad )
    {     
     if ( touchZone.Contains( touch.position ) )
      shouldLatchFinger = true;
    }
    else if ( gui.HitTest( touch.position ) )
    {
     shouldLatchFinger = true;
    }   
   
    // Latch the finger if this is a new touch
    if ( shouldLatchFinger && ( lastFingerId == -1 || lastFingerId != touch.fingerId ) )
    {
      
     if ( touchPad )
     {
      gui.color.a = 0.15;
       
      lastFingerId = touch.fingerId;
      fingerDownPos = touch.position;
      fingerDownTime = Time.time;
     }
      
     lastFingerId = touch.fingerId;
      
     // Accumulate taps if it is within the time window
     if ( tapTimeWindow > 0 )
      tapCount++;
     else
     {
      tapCount = 1;
      tapTimeWindow = tapTimeDelta;
     }
                              
     // Tell other joysticks we've latched this finger
     for ( var j : Joystick in joysticks )
     {
      if ( j != this )
       j.LatchedFinger( touch.fingerId );
     }       
    }     
   
    if ( lastFingerId == touch.fingerId )
    {  
     // Override the tap count with what the iPhone SDK reports if it is greater
     // This is a workaround, since the iPhone SDK does not currently track taps
     // for multiple touches
     if ( touch.tapCount > tapCount )
      tapCount = touch.tapCount;
      
     if ( touchPad )
     {  
      // For a touchpad, let's just set the position directly based on distance from initial touchdown
      position.x = Mathf.Clamp( ( touch.position.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );
      position.y = Mathf.Clamp( ( touch.position.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );
     }
     else
     {      
      // Change the location of the joystick graphic to match where the touch is
      gui.pixelInset.x =  Mathf.Clamp( guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x );
      gui.pixelInset.y =  Mathf.Clamp( guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y );   
     }
      
     if ( touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled )
      ResetJoystick();      
    }    
   }
  }
   
  if ( !touchPad )
  {
   // Get a value between -1 and 1 based on the joystick graphic location
   position.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;
   position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;
  }
   
  // Adjust for dead zone  
  var absoluteX = Mathf.Abs( position.x );
  var absoluteY = Mathf.Abs( position.y );
   
  if ( absoluteX < deadZone.x )
  {
   // Report the joystick as being at the center if it is within the dead zone
   position.x = 0;
  }
  else if ( normalize )
  {
   // Rescale the output after taking the dead zone into account
   position.x = Mathf.Sign( position.x ) * ( absoluteX - deadZone.x ) / ( 1 - deadZone.x );
  }
    
  if ( absoluteY < deadZone.y )
  {
   // Report the joystick as being at the center if it is within the dead zone
   position.y = 0;
  }
  else if ( normalize )
  {
   // Rescale the output after taking the dead zone into account
   position.y = Mathf.Sign( position.y ) * ( absoluteY - deadZone.y ) / ( 1 - deadZone.y );
  }
}


Код
#pragma strict

@script RequireComponent( CharacterController )

// This script must be attached to a GameObject that has a CharacterController
var moveTouchPad : Joystick;
var rotateTouchPad : Joystick;      // If unassigned, tilt is used

var cameraPivot : Transform;      // The transform used for camera rotation

var forwardSpeed : float = 4;
var backwardSpeed : float = 1;
var sidestepSpeed : float = 1;
var jumpSpeed : float = 8;
var inAirMultiplier : float = 0.25;     // Limiter for ground speed while jumping
var rotationSpeed : Vector2 = Vector2( 50, 25 );    // Camera rotation speed for each axis
var tiltPositiveYAxis = 0.6;
var tiltNegativeYAxis = 0.4;
var tiltXAxisMinimum = 0.1;

private var thisTransform : Transform;
private var character : CharacterController;
private var cameraVelocity : Vector3;
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();
   
  if ( rotateTouchPad )
   rotateTouchPad.Disable();  

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

function Update()
{
  var movement = thisTransform.TransformDirection( Vector3( moveTouchPad.position.x, 0, moveTouchPad.position.y ) );

  // We only want horizontal movement
  movement.y = 0;
  movement.Normalize();

  // Apply movement from move joystick
  var absJoyPos = Vector2( Mathf.Abs( moveTouchPad.position.x ), Mathf.Abs( moveTouchPad.position.y ) );  
  if ( absJoyPos.y > absJoyPos.x )
  {
   if ( moveTouchPad.position.y > 0 )
    movement *= forwardSpeed * absJoyPos.y;
   else
    movement *= backwardSpeed * absJoyPos.y;
  }
  else
   movement *= sidestepSpeed * absJoyPos.x;   
   
  // Check for jump
  if ( character.isGrounded )
  {   
   var jump = false;
   var touchPad : Joystick;
   if ( rotateTouchPad )
    touchPad = rotateTouchPad;
   else
    touchPad = moveTouchPad;
   
   if ( !touchPad.IsFingerDown() )
    canJump = true;
    
    if ( canJump && touchPad.tapCount >= 2 )
    {
    jump = true;
    canJump = false;
    }  
    
   if ( jump )
   {
    // Apply the current movement to launch velocity   
    velocity = character.velocity;
    velocity.y = jumpSpeed;  
   }
  }
  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;
   
  // Apply rotation from rotation joystick
  if ( character.isGrounded )
  {
   var camRotation = Vector2.zero;
    
   if ( rotateTouchPad )
    camRotation = rotateTouchPad.position;
   else
   {
    // Use tilt instead
//   print( iPhoneInput.acceleration );
    var acceleration = Input.acceleration;
    var absTiltX = Mathf.Abs( acceleration.x );
    if ( acceleration.z < 0 && acceleration.x < 0 )
    {
     if ( absTiltX >= tiltPositiveYAxis )
      camRotation.y = (absTiltX - tiltPositiveYAxis) / (1 - tiltPositiveYAxis);
     else if ( absTiltX <= tiltNegativeYAxis )
      camRotation.y = -( tiltNegativeYAxis - absTiltX) / tiltNegativeYAxis;
    }
     
    if ( Mathf.Abs( acceleration.y ) >= tiltXAxisMinimum )
     camRotation.x = -(acceleration.y - tiltXAxisMinimum) / (1 - tiltXAxisMinimum);
   }
    
   camRotation.x *= rotationSpeed.x;
   camRotation.y *= rotationSpeed.y;
   camRotation *= Time.deltaTime;
    
   // Rotate the character around world-y using x-axis of joystick
   thisTransform.Rotate( 0, camRotation.x, 0, Space.World );
    
   // Rotate only the camera with y-axis input
   cameraPivot.Rotate( -camRotation.y, 0, 0 );
  }
}


Я их просматривал, но не въехал где копать ...

Добавлено (21 Апр 2014, 13:20)
---------------------------------------------
Вот, например, в Dead Trigger и других нормальных FPS для Андроида правый тач нормально управляет камерой, т.е. как пальцем ведёшь - так камера и вертится, без задержек, инерции и прочих боков ... А со стандартным тачем в Юне так не получается ... Камеру как-то то сильно заносит, то, наоборот, не повернёшь быстро. Вот нажал пальцем, вправо провёл и , вроде бы, быстро повернулась камера, а, если неотпуская палец, влево провести, то намного медленнее получается ...

Добавлено (22 Апр 2014, 11:34)
---------------------------------------------
Так что, нет вариантов ? ... sad

Добавлено (24 Апр 2014, 16:52)
---------------------------------------------
Тема актуальна !!!

Добавлено (24 Апр 2014, 18:48)
---------------------------------------------
Мне кажется, что Я понял в чём проблема ... Я обратил внимание, что тач крутит камеру даже после остановки пальца, а нужно, чтобы она крутилась только пока палец двигается по экрану. И ещё заметил, что даже , если просто поставить палец на экран и не двигать, то камера по-тихоньку смещается ... Как это исправить ?

 
СообщениеНу, Я использую стандартный Фёст Персон Контрол из Станд.АссетсМобайл, и так понимаю, что этим делом управляет либо скрипт Joystick , либо FirstPersonControl ...
Код
#pragma strict

@script RequireComponent( GUITexture )

// A simple class for bounding how far the GUITexture will move
class Boundary  
{
  var min : Vector2 = Vector2.zero;
  var max : Vector2 = Vector2.zero;
}

static private var joysticks : Joystick[];     // A static collection of all joysticks
static private var enumeratedJoysticks : boolean = false;
static private var tapTimeDelta : float = 0.3;    // Time allowed between taps

var touchPad : boolean;          // Is this a TouchPad?
var touchZone : Rect;
var deadZone : Vector2 = Vector2.zero;      // Control when position is output
var normalize : boolean = false;        // Normalize output after the dead-zone?
var position : Vector2;          // [-1, 1] in x,y
var tapCount : int;                              // Current tap count

private var lastFingerId = -1;        // Finger last used for this joystick
private var tapTimeWindow : float;       // How much time there is left for a tap to occur
private var fingerDownPos : Vector2;
private var fingerDownTime : float;
private var firstDeltaTime : float = 0.5;

private var gui : GUITexture;        // Joystick graphic
private var defaultRect : Rect;        // Default position / extents of the joystick graphic
private var guiBoundary : Boundary = Boundary();   // Boundary for joystick graphic
private var guiTouchOffset : Vector2;      // Offset to apply to touch input
private var guiCenter : Vector2;       // Center of joystick

function Start()
{
  // Cache this component at startup instead of looking up every frame  
  gui = GetComponent( GUITexture );
   
  // Store the default rect for the gui, so we can snap back to it
  defaultRect = gui.pixelInset;  
      
     defaultRect.x += transform.position.x * Screen.width;// + gui.pixelInset.x; // -  Screen.width * 0.5;
     defaultRect.y += transform.position.y * Screen.height;// - Screen.height * 0.5;
      
     transform.position.x = 0.0;
     transform.position.y = 0.0;
          
  if ( touchPad )
  {
   // If a texture has been assigned, then use the rect ferom the gui as our touchZone
   if ( gui.texture )
    touchZone = defaultRect;
  }
  else
  {     
   // This is an offset for touch input to match with the top left
   // corner of the GUI
   guiTouchOffset.x = defaultRect.width * 0.5;
   guiTouchOffset.y = defaultRect.height * 0.5;
    
   // Cache the center of the GUI, since it doesn't change
   guiCenter.x = defaultRect.x + guiTouchOffset.x;
   guiCenter.y = defaultRect.y + guiTouchOffset.y;
    
   // Let's build the GUI boundary, so we can clamp joystick movement
   guiBoundary.min.x = defaultRect.x - guiTouchOffset.x;
   guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;
   guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;
   guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;
  }
}

function Disable()
{
  gameObject.SetActive(false);
  enumeratedJoysticks = false;
}

function ResetJoystick()
{
  // Release the finger control and set the joystick back to the default position
  gui.pixelInset = defaultRect;
  lastFingerId = -1;
  position = Vector2.zero;
  fingerDownPos = Vector2.zero;
   
  if ( touchPad )
   gui.color.a = 0.025;  
}

function IsFingerDown() : boolean
{
  return (lastFingerId != -1);
}
   
function LatchedFinger( fingerId : int )
{
  // If another joystick has latched this finger, then we must release it
  if ( lastFingerId == fingerId )
   ResetJoystick();
}

function Update()
{  
  if ( !enumeratedJoysticks )
  {
   // Collect all joysticks in the game, so we can relay finger latching messages
   joysticks = FindObjectsOfType( Joystick ) as Joystick[];
   enumeratedJoysticks = true;
  }  
    
  var count = Input.touchCount;
   
  // Adjust the tap time window while it still available
  if ( tapTimeWindow > 0 )
   tapTimeWindow -= Time.deltaTime;
  else
   tapCount = 0;
   
  if ( count == 0 )
   ResetJoystick();
  else
  {
   for(var i : int = 0;i < count; i++)
   {
    var touch : Touch = Input.GetTouch(i);    
    var guiTouchPos : Vector2 = touch.position - guiTouchOffset;
   
    var shouldLatchFinger = false;
    if ( touchPad )
    {     
     if ( touchZone.Contains( touch.position ) )
      shouldLatchFinger = true;
    }
    else if ( gui.HitTest( touch.position ) )
    {
     shouldLatchFinger = true;
    }   
   
    // Latch the finger if this is a new touch
    if ( shouldLatchFinger && ( lastFingerId == -1 || lastFingerId != touch.fingerId ) )
    {
      
     if ( touchPad )
     {
      gui.color.a = 0.15;
       
      lastFingerId = touch.fingerId;
      fingerDownPos = touch.position;
      fingerDownTime = Time.time;
     }
      
     lastFingerId = touch.fingerId;
      
     // Accumulate taps if it is within the time window
     if ( tapTimeWindow > 0 )
      tapCount++;
     else
     {
      tapCount = 1;
      tapTimeWindow = tapTimeDelta;
     }
                              
     // Tell other joysticks we've latched this finger
     for ( var j : Joystick in joysticks )
     {
      if ( j != this )
       j.LatchedFinger( touch.fingerId );
     }       
    }     
   
    if ( lastFingerId == touch.fingerId )
    {  
     // Override the tap count with what the iPhone SDK reports if it is greater
     // This is a workaround, since the iPhone SDK does not currently track taps
     // for multiple touches
     if ( touch.tapCount > tapCount )
      tapCount = touch.tapCount;
      
     if ( touchPad )
     {  
      // For a touchpad, let's just set the position directly based on distance from initial touchdown
      position.x = Mathf.Clamp( ( touch.position.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );
      position.y = Mathf.Clamp( ( touch.position.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );
     }
     else
     {      
      // Change the location of the joystick graphic to match where the touch is
      gui.pixelInset.x =  Mathf.Clamp( guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x );
      gui.pixelInset.y =  Mathf.Clamp( guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y );   
     }
      
     if ( touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled )
      ResetJoystick();      
    }    
   }
  }
   
  if ( !touchPad )
  {
   // Get a value between -1 and 1 based on the joystick graphic location
   position.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;
   position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;
  }
   
  // Adjust for dead zone  
  var absoluteX = Mathf.Abs( position.x );
  var absoluteY = Mathf.Abs( position.y );
   
  if ( absoluteX < deadZone.x )
  {
   // Report the joystick as being at the center if it is within the dead zone
   position.x = 0;
  }
  else if ( normalize )
  {
   // Rescale the output after taking the dead zone into account
   position.x = Mathf.Sign( position.x ) * ( absoluteX - deadZone.x ) / ( 1 - deadZone.x );
  }
    
  if ( absoluteY < deadZone.y )
  {
   // Report the joystick as being at the center if it is within the dead zone
   position.y = 0;
  }
  else if ( normalize )
  {
   // Rescale the output after taking the dead zone into account
   position.y = Mathf.Sign( position.y ) * ( absoluteY - deadZone.y ) / ( 1 - deadZone.y );
  }
}


Код
#pragma strict

@script RequireComponent( CharacterController )

// This script must be attached to a GameObject that has a CharacterController
var moveTouchPad : Joystick;
var rotateTouchPad : Joystick;      // If unassigned, tilt is used

var cameraPivot : Transform;      // The transform used for camera rotation

var forwardSpeed : float = 4;
var backwardSpeed : float = 1;
var sidestepSpeed : float = 1;
var jumpSpeed : float = 8;
var inAirMultiplier : float = 0.25;     // Limiter for ground speed while jumping
var rotationSpeed : Vector2 = Vector2( 50, 25 );    // Camera rotation speed for each axis
var tiltPositiveYAxis = 0.6;
var tiltNegativeYAxis = 0.4;
var tiltXAxisMinimum = 0.1;

private var thisTransform : Transform;
private var character : CharacterController;
private var cameraVelocity : Vector3;
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();
   
  if ( rotateTouchPad )
   rotateTouchPad.Disable();  

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

function Update()
{
  var movement = thisTransform.TransformDirection( Vector3( moveTouchPad.position.x, 0, moveTouchPad.position.y ) );

  // We only want horizontal movement
  movement.y = 0;
  movement.Normalize();

  // Apply movement from move joystick
  var absJoyPos = Vector2( Mathf.Abs( moveTouchPad.position.x ), Mathf.Abs( moveTouchPad.position.y ) );  
  if ( absJoyPos.y > absJoyPos.x )
  {
   if ( moveTouchPad.position.y > 0 )
    movement *= forwardSpeed * absJoyPos.y;
   else
    movement *= backwardSpeed * absJoyPos.y;
  }
  else
   movement *= sidestepSpeed * absJoyPos.x;   
   
  // Check for jump
  if ( character.isGrounded )
  {   
   var jump = false;
   var touchPad : Joystick;
   if ( rotateTouchPad )
    touchPad = rotateTouchPad;
   else
    touchPad = moveTouchPad;
   
   if ( !touchPad.IsFingerDown() )
    canJump = true;
    
    if ( canJump && touchPad.tapCount >= 2 )
    {
    jump = true;
    canJump = false;
    }  
    
   if ( jump )
   {
    // Apply the current movement to launch velocity   
    velocity = character.velocity;
    velocity.y = jumpSpeed;  
   }
  }
  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;
   
  // Apply rotation from rotation joystick
  if ( character.isGrounded )
  {
   var camRotation = Vector2.zero;
    
   if ( rotateTouchPad )
    camRotation = rotateTouchPad.position;
   else
   {
    // Use tilt instead
//   print( iPhoneInput.acceleration );
    var acceleration = Input.acceleration;
    var absTiltX = Mathf.Abs( acceleration.x );
    if ( acceleration.z < 0 && acceleration.x < 0 )
    {
     if ( absTiltX >= tiltPositiveYAxis )
      camRotation.y = (absTiltX - tiltPositiveYAxis) / (1 - tiltPositiveYAxis);
     else if ( absTiltX <= tiltNegativeYAxis )
      camRotation.y = -( tiltNegativeYAxis - absTiltX) / tiltNegativeYAxis;
    }
     
    if ( Mathf.Abs( acceleration.y ) >= tiltXAxisMinimum )
     camRotation.x = -(acceleration.y - tiltXAxisMinimum) / (1 - tiltXAxisMinimum);
   }
    
   camRotation.x *= rotationSpeed.x;
   camRotation.y *= rotationSpeed.y;
   camRotation *= Time.deltaTime;
    
   // Rotate the character around world-y using x-axis of joystick
   thisTransform.Rotate( 0, camRotation.x, 0, Space.World );
    
   // Rotate only the camera with y-axis input
   cameraPivot.Rotate( -camRotation.y, 0, 0 );
  }
}


Я их просматривал, но не въехал где копать ...

Добавлено (21 Апр 2014, 13:20)
---------------------------------------------
Вот, например, в Dead Trigger и других нормальных FPS для Андроида правый тач нормально управляет камерой, т.е. как пальцем ведёшь - так камера и вертится, без задержек, инерции и прочих боков ... А со стандартным тачем в Юне так не получается ... Камеру как-то то сильно заносит, то, наоборот, не повернёшь быстро. Вот нажал пальцем, вправо провёл и , вроде бы, быстро повернулась камера, а, если неотпуская палец, влево провести, то намного медленнее получается ...

Добавлено (22 Апр 2014, 11:34)
---------------------------------------------
Так что, нет вариантов ? ... sad

Добавлено (24 Апр 2014, 16:52)
---------------------------------------------
Тема актуальна !!!

Добавлено (24 Апр 2014, 18:48)
---------------------------------------------
Мне кажется, что Я понял в чём проблема ... Я обратил внимание, что тач крутит камеру даже после остановки пальца, а нужно, чтобы она крутилась только пока палец двигается по экрану. И ещё заметил, что даже , если просто поставить палец на экран и не двигать, то камера по-тихоньку смещается ... Как это исправить ?


Автор - dostalition
Дата добавления - 24 Апр 2014 в 18:48
игнатДата: Чт, 24 Апр 2014, 20:06 | Сообщение # 4
 
Сообщений: 706
Награды: 0
Репутация: 107
Статус: Offline
Придумать свою систему.
И кто сказал, что вращаться должно так, как у всех?



Правила форума · участник GCC
 
СообщениеПридумать свою систему.
И кто сказал, что вращаться должно так, как у всех?

Автор - игнат
Дата добавления - 24 Апр 2014 в 20:06
dostalitionДата: Пт, 25 Апр 2014, 09:56 | Сообщение # 5
 
Сообщений: 155
Награды: 0
Репутация: 9
Статус: Offline
Слышь, дружище, ну какого х.. Ты вставил сюда эти две строчки ? Думаешь Я тут задавал бы подобные вопросы, если бы мог сам написать свой контроллер ? Что за люди : помочь не могут, так лишь бы что-то влепить ...

Добавлено (25 Апр 2014, 09:56)
---------------------------------------------
Ну, всё-таки, получается, что эту проверку нужно вставлять в контроллере ... Вот скрипт
Код
   #pragma strict   

   @script RequireComponent( CharacterController )   

   // This script must be attached to a GameObject that has a CharacterController   
   var moveTouchPad : Joystick;   
   var rotateTouchPad : Joystick;      // If unassigned, tilt is used   

   var cameraPivot : Transform;      // The transform used for camera rotation   

   var forwardSpeed : float = 4;   
   var backwardSpeed : float = 1;   
   var sidestepSpeed : float = 1;   
   var jumpSpeed : float = 8;   
   var inAirMultiplier : float = 0.25;     // Limiter for ground speed while jumping   
   var rotationSpeed : Vector2 = Vector2( 50, 25 );    // Camera rotation speed for each axis   
   var tiltPositiveYAxis = 0.6;   
   var tiltNegativeYAxis = 0.4;   
   var tiltXAxisMinimum = 0.1;   

   private var thisTransform : Transform;   
   private var character : CharacterController;   
   private var cameraVelocity : Vector3;   
   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();   
       
    if ( rotateTouchPad )   
     rotateTouchPad.Disable();    

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

   function Update()   
   {   
    var movement = thisTransform.TransformDirection( Vector3( moveTouchPad.position.x, 0, moveTouchPad.position.y ) );   

    // We only want horizontal movement   
    movement.y = 0;   
    movement.Normalize();   

    // Apply movement from move joystick   
    var absJoyPos = Vector2( Mathf.Abs( moveTouchPad.position.x ), Mathf.Abs( moveTouchPad.position.y ) );    
    if ( absJoyPos.y > absJoyPos.x )   
    {   
     if ( moveTouchPad.position.y > 0 )   
      movement *= forwardSpeed * absJoyPos.y;   
     else   
      movement *= backwardSpeed * absJoyPos.y;   
    }   
    else   
     movement *= sidestepSpeed * absJoyPos.x;     
       
    // Check for jump   
    if ( character.isGrounded )   
    {     
     var jump = false;   
     var touchPad : Joystick;   
     if ( rotateTouchPad )   
      touchPad = rotateTouchPad;   
     else   
      touchPad = moveTouchPad;   
       
     if ( !touchPad.IsFingerDown() )   
      canJump = true;   
        
      if ( canJump && touchPad.tapCount >= 2 )   
      {   
      jump = true;   
      canJump = false;   
      }    
        
     if ( jump )   
     {   
      // Apply the current movement to launch velocity     
      velocity = character.velocity;   
      velocity.y = jumpSpeed;    
     }   
    }   
    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;   
       
    // Apply rotation from rotation joystick   
    if ( character.isGrounded )   
    {   
     var camRotation = Vector2.zero;   
        
     if ( rotateTouchPad )   
      camRotation = rotateTouchPad.position;   
     else   
     {   
      // Use tilt instead   
   //   print( iPhoneInput.acceleration );   
      var acceleration = Input.acceleration;   
      var absTiltX = Mathf.Abs( acceleration.x );   
      if ( acceleration.z < 0 && acceleration.x < 0 )   
      {   
       if ( absTiltX >= tiltPositiveYAxis )   
        camRotation.y = (absTiltX - tiltPositiveYAxis) / (1 - tiltPositiveYAxis);   
       else if ( absTiltX <= tiltNegativeYAxis )   
        camRotation.y = -( tiltNegativeYAxis - absTiltX) / tiltNegativeYAxis;   
      }   
         
      if ( Mathf.Abs( acceleration.y ) >= tiltXAxisMinimum )   
       camRotation.x = -(acceleration.y - tiltXAxisMinimum) / (1 - tiltXAxisMinimum);   
     }   
        
     camRotation.x *= rotationSpeed.x;   
     camRotation.y *= rotationSpeed.y;   
     camRotation *= Time.deltaTime;   
        
     // Rotate the character around world-y using x-axis of joystick   
     thisTransform.Rotate( 0, camRotation.x, 0, Space.World );   
        
     // Rotate only the camera with y-axis input   
     cameraPivot.Rotate( -camRotation.y, 0, 0 );   
    }   
   }
Кто подскажет куда именно ? Т.е. , видимо, нужно сделать ссылку на переменную touch из скрипта Joystick и в скрипте контроллера делать из неё условие на вращение, не ясно только где именно его делать ... sad


Сообщение отредактировал dostalition - Пт, 25 Апр 2014, 09:57
 
СообщениеСлышь, дружище, ну какого х.. Ты вставил сюда эти две строчки ? Думаешь Я тут задавал бы подобные вопросы, если бы мог сам написать свой контроллер ? Что за люди : помочь не могут, так лишь бы что-то влепить ...

Добавлено (25 Апр 2014, 09:56)
---------------------------------------------
Ну, всё-таки, получается, что эту проверку нужно вставлять в контроллере ... Вот скрипт
Код
   #pragma strict   

   @script RequireComponent( CharacterController )   

   // This script must be attached to a GameObject that has a CharacterController   
   var moveTouchPad : Joystick;   
   var rotateTouchPad : Joystick;      // If unassigned, tilt is used   

   var cameraPivot : Transform;      // The transform used for camera rotation   

   var forwardSpeed : float = 4;   
   var backwardSpeed : float = 1;   
   var sidestepSpeed : float = 1;   
   var jumpSpeed : float = 8;   
   var inAirMultiplier : float = 0.25;     // Limiter for ground speed while jumping   
   var rotationSpeed : Vector2 = Vector2( 50, 25 );    // Camera rotation speed for each axis   
   var tiltPositiveYAxis = 0.6;   
   var tiltNegativeYAxis = 0.4;   
   var tiltXAxisMinimum = 0.1;   

   private var thisTransform : Transform;   
   private var character : CharacterController;   
   private var cameraVelocity : Vector3;   
   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();   
       
    if ( rotateTouchPad )   
     rotateTouchPad.Disable();    

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

   function Update()   
   {   
    var movement = thisTransform.TransformDirection( Vector3( moveTouchPad.position.x, 0, moveTouchPad.position.y ) );   

    // We only want horizontal movement   
    movement.y = 0;   
    movement.Normalize();   

    // Apply movement from move joystick   
    var absJoyPos = Vector2( Mathf.Abs( moveTouchPad.position.x ), Mathf.Abs( moveTouchPad.position.y ) );    
    if ( absJoyPos.y > absJoyPos.x )   
    {   
     if ( moveTouchPad.position.y > 0 )   
      movement *= forwardSpeed * absJoyPos.y;   
     else   
      movement *= backwardSpeed * absJoyPos.y;   
    }   
    else   
     movement *= sidestepSpeed * absJoyPos.x;     
       
    // Check for jump   
    if ( character.isGrounded )   
    {     
     var jump = false;   
     var touchPad : Joystick;   
     if ( rotateTouchPad )   
      touchPad = rotateTouchPad;   
     else   
      touchPad = moveTouchPad;   
       
     if ( !touchPad.IsFingerDown() )   
      canJump = true;   
        
      if ( canJump && touchPad.tapCount >= 2 )   
      {   
      jump = true;   
      canJump = false;   
      }    
        
     if ( jump )   
     {   
      // Apply the current movement to launch velocity     
      velocity = character.velocity;   
      velocity.y = jumpSpeed;    
     }   
    }   
    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;   
       
    // Apply rotation from rotation joystick   
    if ( character.isGrounded )   
    {   
     var camRotation = Vector2.zero;   
        
     if ( rotateTouchPad )   
      camRotation = rotateTouchPad.position;   
     else   
     {   
      // Use tilt instead   
   //   print( iPhoneInput.acceleration );   
      var acceleration = Input.acceleration;   
      var absTiltX = Mathf.Abs( acceleration.x );   
      if ( acceleration.z < 0 && acceleration.x < 0 )   
      {   
       if ( absTiltX >= tiltPositiveYAxis )   
        camRotation.y = (absTiltX - tiltPositiveYAxis) / (1 - tiltPositiveYAxis);   
       else if ( absTiltX <= tiltNegativeYAxis )   
        camRotation.y = -( tiltNegativeYAxis - absTiltX) / tiltNegativeYAxis;   
      }   
         
      if ( Mathf.Abs( acceleration.y ) >= tiltXAxisMinimum )   
       camRotation.x = -(acceleration.y - tiltXAxisMinimum) / (1 - tiltXAxisMinimum);   
     }   
        
     camRotation.x *= rotationSpeed.x;   
     camRotation.y *= rotationSpeed.y;   
     camRotation *= Time.deltaTime;   
        
     // Rotate the character around world-y using x-axis of joystick   
     thisTransform.Rotate( 0, camRotation.x, 0, Space.World );   
        
     // Rotate only the camera with y-axis input   
     cameraPivot.Rotate( -camRotation.y, 0, 0 );   
    }   
   }
Кто подскажет куда именно ? Т.е. , видимо, нужно сделать ссылку на переменную touch из скрипта Joystick и в скрипте контроллера делать из неё условие на вращение, не ясно только где именно его делать ... sad

Автор - dostalition
Дата добавления - 25 Апр 2014 в 09:56
Форум Игроделов » UNITY3D » ОБЩИЕ ВОПРОСЫ » Настройка FPC-камеры на Андроиде
  • Страница 1 из 1
  • 1
Поиск:
Загрузка...

Game Creating CommUnity © 2009 - 2024