Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- public class ShipController : MonoBehaviour {
- public float speed = 10.0f;
- // The clamp margins
- public float
- clampMarginMinX = 10.0f,
- clampMarginMaxX = 10.0f,
- clampMarginMinY = 10.0f,
- clampMarginMaxY = 10.0f,
- // The minimum and maximum values which the object can go
- m_clampMinX,
- m_clampMaxX,
- m_clampMinY,
- m_clampMaxY;
- private void Start()
- {
- // Get the minimum and maximum position values according to the screen size represented by the main camera.
- m_clampMinX = Camera.main.ScreenToWorldPoint(new Vector2(0 + clampMarginMinX, 0)).x;
- m_clampMaxX = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width - clampMarginMaxX, 0)).x;
- m_clampMinY = Camera.main.ScreenToWorldPoint(new Vector2(0, 0 + clampMarginMinY)).y;
- m_clampMaxY = Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height + clampMarginMaxY)).y;
- }
- private void Update()
- {
- Vector3 direction = Vector3.zero;
- // Going left
- if (Input.GetKey(KeyCode.A))
- {
- direction = Vector2.right * -1;
- }
- // Going right
- else if (Input.GetKey(KeyCode.D))
- {
- direction = Vector2.right;
- }
- if (transform.position.x < m_clampMinX)
- {
- // If the object position tries to exceed the left screen bound clamp the min x position to 0.
- // The maximum x position won't be clamped so the object can move to the right.
- direction.x = Mathf.Clamp(direction.x, 0, Mathf.Infinity);
- }
- if (transform.position.x > m_clampMaxX)
- {
- // Same goes here
- direction.x = Mathf.Clamp(direction.x, Mathf.NegativeInfinity, 0);
- }
- transform.position += direction * (Time.deltaTime * speed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement