Advertisement
Guest User

Untitled

a guest
Sep 29th, 2014
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using System.Collections.Generic;
  5.  
  6. public class ShipController : MonoBehaviour {
  7.     public float speed = 10.0f;
  8.    
  9.     // The clamp margins
  10.     public float
  11.         clampMarginMinX = 10.0f,
  12.         clampMarginMaxX = 10.0f,
  13.         clampMarginMinY = 10.0f,
  14.         clampMarginMaxY = 10.0f,
  15.    
  16.     // The minimum and maximum values which the object can go
  17.  
  18.         m_clampMinX,
  19.         m_clampMaxX,
  20.         m_clampMinY,
  21.         m_clampMaxY;
  22.    
  23.     private void Start()
  24.     {
  25.         // Get the minimum and maximum position values according to the screen size represented by the main camera.
  26.         m_clampMinX = Camera.main.ScreenToWorldPoint(new Vector2(0 + clampMarginMinX, 0)).x;
  27.         m_clampMaxX = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width - clampMarginMaxX, 0)).x;
  28.         m_clampMinY = Camera.main.ScreenToWorldPoint(new Vector2(0, 0 + clampMarginMinY)).y;
  29.         m_clampMaxY = Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height + clampMarginMaxY)).y;
  30.     }
  31.    
  32.     private void Update()
  33.     {
  34.         Vector3 direction = Vector3.zero;
  35.        
  36.         // Going left
  37.         if (Input.GetKey(KeyCode.A))
  38.         {
  39.             direction = Vector2.right * -1;
  40.         }
  41.        
  42.         // Going right
  43.         else if (Input.GetKey(KeyCode.D))
  44.         {
  45.             direction = Vector2.right;
  46.         }
  47.        
  48.         if (transform.position.x < m_clampMinX)
  49.         {
  50.             // If the object position tries to exceed the left screen bound clamp the min x position to 0.
  51.             // The maximum x position won't be clamped so the object can move to the right.
  52.             direction.x = Mathf.Clamp(direction.x, 0, Mathf.Infinity);
  53.         }
  54.        
  55.         if (transform.position.x > m_clampMaxX)
  56.         {
  57.             // Same goes here
  58.             direction.x = Mathf.Clamp(direction.x, Mathf.NegativeInfinity, 0);
  59.         }
  60.        
  61.         transform.position += direction * (Time.deltaTime * speed);
  62.     }
  63.    
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement