public static tk2dSpriteCollectionSize ForTk2dCamera(tk2dCamera camera) { tk2dSpriteCollectionSize size = new tk2dSpriteCollectionSize(); tk2dCameraSettings cameraSettings = camera.SettingsRoot.CameraSettings; if (cameraSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic) { tk2dCameraSettings.OrthographicType orthographicType = cameraSettings.orthographicType; if (orthographicType != tk2dCameraSettings.OrthographicType.PixelsPerMeter) { if (orthographicType != tk2dCameraSettings.OrthographicType.OrthographicSize) { return size; } } else { size.type = Type.PixelsPerMeter; size.pixelsPerMeter = cameraSettings.orthographicPixelsPerMeter; return size; } size.type = Type.Explicit; size.height = camera.nativeResolutionHeight; size.orthoSize = cameraSettings.orthographicSize; return size; } if (cameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { size.type = Type.PixelsPerMeter; size.pixelsPerMeter = 100f; } return size; }
//tk2dCamera cam public void Initalize(tk2dCamera cam){ curtain = transform.GetChild(0).GetComponent<Curtain_>(); ani = transform.GetChild(1).GetComponent<LoadingAni_>(); curtain.Initialize(cam.nativeResolutionWidth, cam.nativeResolutionHeight, cam.CameraSettings.orthographicPixelsPerMeter / 20); ani.Initialize(cam.nativeResolutionWidth, cam.nativeResolutionHeight, cam.CameraSettings.orthographicPixelsPerMeter); enabled = true; }
// Use this for initialization void Start() { score=0; curHP=totalHP; preFireTime=Time.time; m_camera=(tk2dCamera)FindObjectOfType(typeof(tk2dCamera)); gunPort=GetComponent<tk2dSpriteAttachPoint>().attachPoints; }
//tk2dCamera cam public void Initalize(tk2dCamera cam){ isInit = true; enabled = true; curtain = transform.GetChild(0).GetComponent<Curtain_>(); ani = transform.GetChild(1).GetComponent<LoadingAni_>(); curtain.Initialize(cam.forceResolution.x, cam.forceResolution.y, cam.CameraSettings.orthographicPixelsPerMeter); ani.Initialize(cam.forceResolution.x, cam.forceResolution.y, cam.CameraSettings.orthographicPixelsPerMeter); }
private void Start() { instance = this; //us = transform; cam = GetComponent<tk2dCamera>(); //minZoom = cam.ZoomFactor; targets = new Transform[maxTargets]; }
void Start() { thisCamera = gameObject.GetComponent<tk2dCamera> (); playerControl = GameObject.FindGameObjectWithTag("Skateboard").GetComponent<PlayerControl> (); // maxZoom = 1 - maxZoom; // minZoom = 1 - minZoom; //minimumZoom = thisCamera.ZoomFactor; }
void Awake() { if(mInstance == null) { mInstance = this; //init stuff mCam = GetComponentInChildren<tk2dCamera>(); mCurDelay = delay; } else { DestroyImmediate(gameObject); } }
private Vector2 GetOffsetForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, Vector2 scale, float width, float height) { Vector2 zero = Vector2.zero; if (currentOverride == null) { return zero; } tk2dCameraResolutionOverride.FitMode fitMode = currentOverride.fitMode; if ((fitMode != tk2dCameraResolutionOverride.FitMode.Constant) && (fitMode == tk2dCameraResolutionOverride.FitMode.Center)) { if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.BottomLeft) { zero = new Vector2(Mathf.Round(((settings.nativeResolutionWidth * scale.x) - width) / 2f), Mathf.Round(((settings.nativeResolutionHeight * scale.y) - height) / 2f)); } return zero; } return -currentOverride.offsetPixels; }
/// <summary> /// Use when you need the sprite to be pixel perfect on a specific tk2dCamera. /// </summary> public static tk2dSpriteCollectionSize ForTk2dCamera( tk2dCamera camera ) { tk2dSpriteCollectionSize s = new tk2dSpriteCollectionSize(); tk2dCameraSettings cameraSettings = camera.SettingsRoot.CameraSettings; if (cameraSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic) { switch (cameraSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.PixelsPerMeter: s.type = Type.PixelsPerMeter; s.pixelsPerMeter = cameraSettings.orthographicPixelsPerMeter; break; case tk2dCameraSettings.OrthographicType.OrthographicSize: s.type = Type.Explicit; s.height = camera.nativeResolutionHeight; s.orthoSize = cameraSettings.orthographicSize; break; } } else if (cameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { s.type = Type.PixelsPerMeter; s.pixelsPerMeter = 100; // some random value } return s; }
void DrawCameraGUI(tk2dCamera target, bool complete) { bool allowProjectionParameters = target.SettingsRoot == target; bool oldGuiEnabled = GUI.enabled; SerializedObject so = this.serializedObject; SerializedObject cam = new SerializedObject( target.camera ); SerializedProperty m_ClearFlags = cam.FindProperty("m_ClearFlags"); SerializedProperty m_BackGroundColor = cam.FindProperty("m_BackGroundColor"); SerializedProperty m_CullingMask = cam.FindProperty("m_CullingMask"); SerializedProperty m_TargetTexture = cam.FindProperty("m_TargetTexture"); SerializedProperty m_Near = cam.FindProperty("near clip plane"); SerializedProperty m_Far = cam.FindProperty("far clip plane"); SerializedProperty m_Depth = cam.FindProperty("m_Depth"); SerializedProperty m_RenderingPath = cam.FindProperty("m_RenderingPath"); SerializedProperty m_HDR = cam.FindProperty("m_HDR"); if (complete) { EditorGUILayout.PropertyField( m_ClearFlags ); EditorGUILayout.PropertyField( m_BackGroundColor ); EditorGUILayout.PropertyField( m_CullingMask ); EditorGUILayout.Space(); } tk2dCameraSettings cameraSettings = target.CameraSettings; tk2dCameraSettings inheritedSettings = target.SettingsRoot.CameraSettings; TransparencySortMode transparencySortMode = inheritedSettings.transparencySortMode; GUI.enabled &= allowProjectionParameters; inheritedSettings.projection = (tk2dCameraSettings.ProjectionType)EditorGUILayout.EnumPopup("Projection", inheritedSettings.projection); EditorGUI.indentLevel++; if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic) { inheritedSettings.orthographicType = (tk2dCameraSettings.OrthographicType)EditorGUILayout.EnumPopup("Type", inheritedSettings.orthographicType); switch (inheritedSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: inheritedSettings.orthographicSize = Mathf.Max( 0.001f, EditorGUILayout.FloatField("Orthographic Size", inheritedSettings.orthographicSize) ); break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: inheritedSettings.orthographicPixelsPerMeter = Mathf.Max( 0.001f, EditorGUILayout.FloatField("Pixels per Meter", inheritedSettings.orthographicPixelsPerMeter) ); break; } inheritedSettings.orthographicOrigin = (tk2dCameraSettings.OrthographicOrigin)EditorGUILayout.EnumPopup("Origin", inheritedSettings.orthographicOrigin); } else if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { inheritedSettings.fieldOfView = EditorGUILayout.Slider("Field of View", inheritedSettings.fieldOfView, 1, 179); transparencySortMode = (TransparencySortMode)EditorGUILayout.EnumPopup("Sort mode", transparencySortMode); } EditorGUI.indentLevel--; GUI.enabled = oldGuiEnabled; if (complete) { EditorGUILayout.Space(); GUILayout.Label("Clipping Planes"); GUILayout.BeginHorizontal(); GUILayout.Space(14); GUILayout.Label("Near"); if (m_Near != null) EditorGUILayout.PropertyField(m_Near, GUIContent.none, GUILayout.Width(60) ); GUILayout.Label("Far"); if (m_Far != null) EditorGUILayout.PropertyField(m_Far, GUIContent.none, GUILayout.Width(60) ); GUILayout.EndHorizontal(); cameraSettings.rect = EditorGUILayout.RectField("Normalized View Port Rect", cameraSettings.rect); EditorGUILayout.Space(); if (m_Depth != null) EditorGUILayout.PropertyField(m_Depth); if (m_RenderingPath != null) EditorGUILayout.PropertyField(m_RenderingPath); if (m_TargetTexture != null) EditorGUILayout.PropertyField(m_TargetTexture); if (m_HDR != null) EditorGUILayout.PropertyField(m_HDR); } cam.ApplyModifiedProperties(); so.ApplyModifiedProperties(); if (transparencySortMode != inheritedSettings.transparencySortMode) { inheritedSettings.transparencySortMode = transparencySortMode; target.camera.transparencySortMode = transparencySortMode; // Change immediately in the editor EditorUtility.SetDirty(target); EditorUtility.SetDirty(target.camera); } }
void UpdateTransform() { // Break out if anchor camera is not bound if (AnchorCamera == null) { return; } float pixelScale = 1; // size of one pixel Vector3 position = myTransform.localPosition; // we're ignoring perspective tk2dCameras for now tk2dCamera = (AnchorTk2dCamera != null && AnchorTk2dCamera.CameraSettings.projection != tk2dCameraSettings.ProjectionType.Perspective) ? AnchorTk2dCamera : null; Rect rect = new Rect(); if (tk2dCamera != null) { rect = anchorToNativeBounds ? tk2dCamera.NativeScreenExtents : tk2dCamera.ScreenExtents; pixelScale = tk2dCamera.GetSizeAtDistance(1); } else { rect.Set(0, 0, AnchorCamera.pixelWidth, AnchorCamera.pixelHeight); } float y_bot = rect.yMin; float y_top = rect.yMax; float y_ctr = (y_bot + y_top) * 0.5f; float x_lhs = rect.xMin; float x_rhs = rect.xMax; float x_ctr = (x_lhs + x_rhs) * 0.5f; Vector3 anchoredPosition = Vector3.zero; switch (AnchorPoint) { case tk2dBaseSprite.Anchor.UpperLeft: anchoredPosition = new Vector3(x_lhs, y_top, position.z); break; case tk2dBaseSprite.Anchor.UpperCenter: anchoredPosition = new Vector3(x_ctr, y_top, position.z); break; case tk2dBaseSprite.Anchor.UpperRight: anchoredPosition = new Vector3(x_rhs, y_top, position.z); break; case tk2dBaseSprite.Anchor.MiddleLeft: anchoredPosition = new Vector3(x_lhs, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.MiddleCenter: anchoredPosition = new Vector3(x_ctr, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.MiddleRight: anchoredPosition = new Vector3(x_rhs, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.LowerLeft: anchoredPosition = new Vector3(x_lhs, y_bot, position.z); break; case tk2dBaseSprite.Anchor.LowerCenter: anchoredPosition = new Vector3(x_ctr, y_bot, position.z); break; case tk2dBaseSprite.Anchor.LowerRight: anchoredPosition = new Vector3(x_rhs, y_bot, position.z); break; } Vector3 screenAnchoredPosition = anchoredPosition + new Vector3(pixelScale * offset.x, pixelScale * offset.y, 0); if (tk2dCamera == null) // not a tk2dCamera, we need to transform { Vector3 worldAnchoredPosition = AnchorCamera.ScreenToWorldPoint(screenAnchoredPosition); if (myTransform.position != worldAnchoredPosition) { myTransform.position = worldAnchoredPosition; } } else { Vector3 oldPosition = myTransform.localPosition; if (oldPosition != screenAnchoredPosition) { myTransform.localPosition = screenAnchoredPosition; } } }
Matrix4x4 GetProjectionMatrixForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float pixelWidth, float pixelHeight, bool halfTexelOffset, out Rect screenExtents, out Rect unscaledScreenExtents) { Vector2 scale = GetScaleForOverride(settings, currentOverride, pixelWidth, pixelHeight); Vector2 offset = GetOffsetForOverride(settings, currentOverride, scale, pixelWidth, pixelHeight); float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; Vector2 nativeResolutionOffset = Vector2.zero; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (this.viewportClippingEnabled && this.InheritConfig != null) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)this.viewportRegion.x, (int)this.viewportRegion.y, (int)this.viewportRegion.z, (int)this.viewportRegion.w); float viewportLeft = -offset.x / pixelWidth + sr.x / vw; float viewportBottom = -offset.y / pixelHeight + sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { viewportLeft += (pixelWidth - settings.nativeResolutionWidth * scale.x) / pixelWidth / 2.0f; viewportBottom += (pixelHeight - settings.nativeResolutionHeight * scale.y) / pixelHeight / 2.0f; } Rect r = new Rect(viewportLeft, viewportBottom, viewportWidth, viewportHeight); if (UnityCamera.rect.x != viewportLeft || UnityCamera.rect.y != viewportBottom || UnityCamera.rect.width != viewportWidth || UnityCamera.rect.height != viewportHeight) { UnityCamera.rect = r; } float maxWidth = Mathf.Min(1.0f - r.x, r.width); float maxHeight = Mathf.Min(1.0f - r.y, r.height); float rectOffsetX = sr.x * scale.x - offset.x; float rectOffsetY = sr.y * scale.y - offset.y; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { rectOffsetX -= settings.nativeResolutionWidth * 0.5f * scale.x; rectOffsetY -= settings.nativeResolutionHeight * 0.5f * scale.y; } if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { if (UnityCamera.rect != CameraSettings.rect) { UnityCamera.rect = CameraSettings.rect; } // By default the camera is orthographic, bottom left, 1 pixel per meter if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { float w = (right - left) * 0.5f; left -= w; right -= w; float h = (top - bottom) * 0.5f; top -= h; bottom -= h; nativeResolutionOffset.Set(-nativeResolutionWidth / 2.0f, -nativeResolutionHeight / 2.0f); } } float zoomScale = 1.0f / ZoomFactor; // Only need the half texel offset on PC/D3D bool needHalfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexel = (halfTexelOffset && needHalfTexelOffset) ? 0.5f : 0.0f; float orthoSize = settings.cameraSettings.orthographicSize; switch (settings.cameraSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: orthoSize = 2.0f * settings.cameraSettings.orthographicSize / settings.nativeResolutionHeight; break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: orthoSize = 1.0f / settings.cameraSettings.orthographicPixelsPerMeter; break; } float s = orthoSize * zoomScale; screenExtents = new Rect(left * s / scale.x, bottom * s / scale.y, (right - left) * s / scale.x, (top - bottom) * s / scale.y); unscaledScreenExtents = new Rect(nativeResolutionOffset.x * s, nativeResolutionOffset.y * s, nativeResolutionWidth * s, nativeResolutionHeight * s); // Near and far clip planes are tweakable per camera, so we pull from current camera instance regardless of inherited values return(OrthoOffCenter(scale, orthoSize * (left + halfTexel) * zoomScale, orthoSize * (right + halfTexel) * zoomScale, orthoSize * (bottom - halfTexel) * zoomScale, orthoSize * (top - halfTexel) * zoomScale, UnityCamera.nearClipPlane, UnityCamera.farClipPlane)); }
Vector2 GetScreenPixelDimensions(tk2dCamera settings) { Vector2 dimensions = new Vector2(ScreenCamera.pixelWidth, ScreenCamera.pixelHeight); #if UNITY_EDITOR // This bit here allocates memory, but only runs in the editor float gameViewPixelWidth = 0, gameViewPixelHeight = 0; float gameViewAspect = 0; settings.useGameWindowResolutionInEditor = false; if (Editor__GetGameViewSize( out gameViewPixelWidth, out gameViewPixelHeight, out gameViewAspect)) { if (gameViewPixelWidth != 0 && gameViewPixelHeight != 0) { if (!settings.useGameWindowResolutionInEditor || settings.gameWindowResolution.x != gameViewPixelWidth || settings.gameWindowResolution.y != gameViewPixelHeight) { settings.useGameWindowResolutionInEditor = true; settings.gameWindowResolution.x = gameViewPixelWidth; settings.gameWindowResolution.y = gameViewPixelHeight; } dimensions.x = settings.gameWindowResolution.x; dimensions.y = settings.gameWindowResolution.y; } } if (!settings.useGameWindowResolutionInEditor && settings.forceResolutionInEditor) { dimensions.x = settings.forceResolution.x; dimensions.y = settings.forceResolution.y; } #endif return dimensions; }
private void applyMask() { Matrix4x4 maskTransform = Matrix4x4.identity; maskTransform.m00 = m_Mask.currentState.a; maskTransform.m01 = m_Mask.currentState.c; maskTransform.m10 = m_Mask.currentState.b; maskTransform.m11 = m_Mask.currentState.d; #if GAF_USING_TK2D float screenHeight = 0; float screenWidth = 0; Vector2 cameraPosShift = Vector2.zero; tk2dCamera tk2d_camera = Camera.current.GetComponent <tk2dCamera>(); if (tk2d_camera != null) { tk2dCameraSettings cameraSettings = tk2d_camera.CameraSettings; if (cameraSettings.orthographicType == tk2dCameraSettings.OrthographicType.PixelsPerMeter) { screenHeight = tk2d_camera.nativeResolutionHeight / cameraSettings.orthographicPixelsPerMeter; } else { screenHeight = tk2d_camera.CameraSettings.orthographicSize * 2; } screenWidth = Camera.current.aspect * screenHeight; cameraPosShift = Camera.current.transform.position - new Vector3(screenWidth / 2f, -screenHeight / 2f); } else { screenHeight = Camera.current.orthographicSize * 2; screenWidth = Camera.current.aspect * screenHeight; cameraPosShift = Camera.current.transform.position - new Vector3(screenWidth / 2f, -screenHeight / 2f); } #else float screenHeight = Camera.current.orthographicSize * 2; float screenWidth = Camera.current.aspect * screenHeight; Vector2 cameraPosShift = Camera.current.transform.position - new Vector3(screenWidth / 2f, -screenHeight / 2f); #endif // GAF_USING_TK2D float scaleX = Mathf.Sqrt((maskTransform.m00 * maskTransform.m00) + (maskTransform.m01 * maskTransform.m01)); float scaleY = Mathf.Sqrt((maskTransform.m11 * maskTransform.m11) + (maskTransform.m10 * maskTransform.m10)); float scale = movieClip.settings.pixelsPerUnit * m_Mask.atlasElement.scale * movieClip.settings.csf; float sizeXUV = (float)screenWidth / (m_Mask.texture.width / scale * scaleX * transform.parent.localScale.x * Camera.current.aspect); float sizeYUV = (float)screenHeight / (m_Mask.texture.height / scale * scaleY * transform.parent.localScale.y); float maskWidth = (float)m_Mask.texture.width / movieClip.settings.csf; float maskHeight = (float)m_Mask.texture.height / movieClip.settings.csf; float pivotX = m_Mask.atlasElement.pivotX / maskWidth; float pivotY = (maskHeight - m_Mask.atlasElement.pivotY) / maskHeight; float moveX = (-m_Mask.transform.position.x + cameraPosShift.x) / screenWidth; float moveY = -1f - (m_Mask.transform.position.y - cameraPosShift.y) / screenHeight; Matrix4x4 _transform = Matrix4x4.identity; _transform *= Matrix4x4.TRS(new Vector3(pivotX, pivotY, 0f), Quaternion.identity, Vector3.one); _transform *= Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(sizeXUV, sizeYUV, 1f)); _transform *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, -transform.parent.localRotation.eulerAngles.z), Vector3.one); _transform *= maskTransform; _transform *= Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1f / scaleX, 1f / scaleY, 1f)); _transform *= Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(Camera.current.aspect, 1f, 1f)); _transform *= Matrix4x4.TRS(new Vector3(moveX, moveY, 0f), Quaternion.identity, Vector3.one); renderer.sharedMaterial.SetMatrix("_TransformMatrix", _transform); renderer.sharedMaterial.SetTexture("_MaskMap", m_Mask.texture); }
protected IsoWorldMode() { mainCamera = Camera.main.GetComponent <tk2dCamera>(); }
void Start() { objCamera = (tk2dCamera)GameObject.FindWithTag("MainCamera").GetComponent <tk2dCamera>(); objLineRenderer = GetComponent <LineRenderer>(); }
void Start() { thisCam = gameObject.GetComponent <tk2dCamera>(); }
void PerformStrike(Collider aCol, Vector3 pos, int chargeInd) { if (mStrikeActives >= mStrikes.Length) { return; } mDmg.amount = mDefaultDmgAmt + ((float)chargeInd); Collider[] cols = Physics.OverlapSphere(pos, radius, masks); if (cols != null && cols.Length > 0) { //get nearest collider Vector3 p = Vector3.zero; Vector3 dir = Vector3.zero; Collider col = null; Stats colStat = null; float nearSqr = Mathf.Infinity; for (int cI = 0, cMax = cols.Length; cI < cMax; cI++) { if (System.Array.IndexOf(mStruckCols, cols[cI], 0, mStrikeActives) != -1) { continue; } if (cols[cI] != aCol && cols[cI].gameObject.activeInHierarchy) { Vector3 _p = cols[cI].bounds.center; Vector3 _dir = _p - pos; float _dist = _dir.sqrMagnitude; if (_dist < nearSqr) { Stats stat = cols[cI].GetComponent <Stats>(); if (stat && stat.CanDamage(mDmg)) { p = _p; dir = _dir; col = cols[cI]; colStat = stat; nearSqr = _dist; } } } } if (col == null) { return; } tk2dCamera cam = CameraController.instance.tk2dCam; float dist = Mathf.Sqrt(nearSqr); dir /= dist; if (mDmg.CallDamageTo(colStat, p, (p - pos).normalized)) { mStrikes[mStrikeActives].SetActive(true); mStrikes[mStrikeActives].transform.parent = null; mStrikes[mStrikeActives].transform.position = pos; mStrikes[mStrikeActives].transform.localScale = Vector3.one; mStrikes[mStrikeActives].transform.up = dir; for (int i = 0, max = mStrikeTileSprites[mStrikeActives].Length; i < max; i++) { Vector2 dim = mStrikeTileSprites[mStrikeActives][i].dimensions; dim.y = dist * cam.CameraSettings.orthographicPixelsPerMeter; mStrikeTileSprites[mStrikeActives][i].dimensions = dim; } mStruckCols[mStrikeActives] = col; mStrikeActives++; if (chargeInd > 0 && mStrikeActives + chargeInd <= mStrikes.Length) { PerformStrike(col, p, chargeInd - 1); } } } }
void DrawOverrideGUI(tk2dCamera _camera) { var frameBorderStyle = EditorStyles.textField; EditorGUIUtility.LookLikeControls(64); tk2dCamera _target = _camera.SettingsRoot; if (_target.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { tk2dGuiUtility.InfoBox("Overrides not supported with perspective camera.", tk2dGuiUtility.WarningLevel.Info); } else { GUI.enabled = _target == _camera; tk2dCameraResolutionOverride usedOverride = _target.CurrentResolutionOverride; if (_target.resolutionOverride.Length == 0) { EditorGUILayout.HelpBox("There are no overrides on this tk2dCamera.\n\nThe camera will always scale itself to be pixel perfect at any resolution. " + "Add an override if you wish to change this behaviour.", MessageType.Warning); } else { EditorGUILayout.HelpBox("Matching is performed from top to bottom. The first override matching the current resolution will be used.", MessageType.Info); } System.Action<int> deferredAction = null; for (int i = 0; i < _target.resolutionOverride.Length; ++i) { tk2dCameraResolutionOverride ovr = _target.resolutionOverride[i]; EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(8); GUILayout.BeginHorizontal(); ovr.name = EditorGUILayout.TextField("Name", ovr.name); GUI.enabled = (i != _target.resolutionOverride.Length - 1); if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_down"))) { int idx = i; deferredAction = delegate(int q) { _target.resolutionOverride[idx] = _target.resolutionOverride[idx+1]; _target.resolutionOverride[idx+1] = ovr; }; } GUI.enabled = (i != 0); if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_up"))) { int idx = i; deferredAction = delegate(int q) { _target.resolutionOverride[idx] = _target.resolutionOverride[idx-1]; _target.resolutionOverride[idx-1] = ovr; }; } GUI.enabled = true; if (GUILayout.Button("", tk2dEditorSkin.GetStyle("TilemapDeleteItem"))) { int idx = i; deferredAction = delegate(int q) { List<tk2dCameraResolutionOverride> list = new List<tk2dCameraResolutionOverride>(_target.resolutionOverride); list.RemoveAt(idx); _target.resolutionOverride = list.ToArray(); }; } GUILayout.EndHorizontal(); ovr.matchBy = (tk2dCameraResolutionOverride.MatchByType)EditorGUILayout.EnumPopup("Match By", ovr.matchBy); int tmpIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; switch (ovr.matchBy) { case tk2dCameraResolutionOverride.MatchByType.Wildcard: break; case tk2dCameraResolutionOverride.MatchByType.Resolution: Vector2 res = new Vector2(ovr.width, ovr.height); res = ResolutionControl(" ", res); ovr.width = (int)res.x; ovr.height = (int)res.y; break; case tk2dCameraResolutionOverride.MatchByType.AspectRatio: GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); ovr.aspectRatioNumerator = EditorGUILayout.FloatField(ovr.aspectRatioNumerator, GUILayout.Width(40)); GUILayout.Label(":", GUILayout.ExpandWidth(false)); ovr.aspectRatioDenominator = EditorGUILayout.FloatField(ovr.aspectRatioDenominator, GUILayout.Width(40)); GUILayout.EndHorizontal(); break; } EditorGUI.indentLevel = tmpIndent; ovr.autoScaleMode = (tk2dCameraResolutionOverride.AutoScaleMode)EditorGUILayout.EnumPopup("Auto Scale", ovr.autoScaleMode); if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.None) { EditorGUI.indentLevel++; ovr.scale = EditorGUILayout.FloatField("Scale", ovr.scale); EditorGUI.indentLevel--; } if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { string msg = "The native resolution image will be stretched to fit the target display. " + "Image quality will suffer if non-uniform scaling occurs."; tk2dGuiUtility.InfoBox(msg, tk2dGuiUtility.WarningLevel.Info); } else { ovr.fitMode = (tk2dCameraResolutionOverride.FitMode)EditorGUILayout.EnumPopup("Fit Mode", ovr.fitMode); if (ovr.fitMode == tk2dCameraResolutionOverride.FitMode.Constant) { EditorGUI.indentLevel++; ovr.offsetPixels.x = EditorGUILayout.FloatField("X", ovr.offsetPixels.x); ovr.offsetPixels.y = EditorGUILayout.FloatField("Y", ovr.offsetPixels.y); EditorGUI.indentLevel--; } } GUILayout.Space(4); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (ovr == usedOverride) { GUI.color = Color.green; GUIContent content = new GUIContent("ACTIVE", "The active override is the one that matches the current resolution, and is being used in the tk2dCamera game window."); GUILayout.Label(content, EditorStyles.miniBoldLabel, GUILayout.ExpandWidth(false)); GUI.color = Color.white; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } if (deferredAction != null) { deferredAction(0); GUI.changed = true; Repaint(); } EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(32); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add override", GUILayout.ExpandWidth(false))) { tk2dCameraResolutionOverride ovr = new tk2dCameraResolutionOverride(); ovr.name = "New override"; ovr.matchBy = tk2dCameraResolutionOverride.MatchByType.Wildcard; ovr.autoScaleMode = tk2dCameraResolutionOverride.AutoScaleMode.FitVisible; ovr.fitMode = tk2dCameraResolutionOverride.FitMode.Center; System.Array.Resize(ref _target.resolutionOverride, _target.resolutionOverride.Length + 1); _target.resolutionOverride[_target.resolutionOverride.Length - 1] = ovr; GUI.changed = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(32); EditorGUILayout.EndVertical(); GUI.enabled = true; } }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// </summary> public void UpdateCameraMatrix() { if (!this.viewportClippingEnabled) inst = this; if (!mainCamera.orthographic) { // Must be orthographic Debug.LogError("tk2dCamera must be orthographic"); mainCamera.orthographic = true; } tk2dCamera settings = inheritSettings != null ? inheritSettings : this; bool viewportClippingEnabled = this.viewportClippingEnabled && this.screenCamera != null && this.screenCamera.rect == unitRect; Camera screenCamera = viewportClippingEnabled ? this.screenCamera : mainCamera; float pixelWidth = screenCamera.pixelWidth; float pixelHeight = screenCamera.pixelHeight; #if UNITY_EDITOR if (settings.forceResolutionInEditor) { pixelWidth = settings.forceResolution.x; pixelHeight = settings.forceResolution.y; } #endif _targetResolution = new Vector2(pixelWidth, pixelHeight); // Find an override if necessary if (!settings.enableResolutionOverrides) currentResolutionOverride = null; if (settings.enableResolutionOverrides && (currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (settings.resolutionOverride != null) { foreach (var ovr in settings.resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } Vector2 scale = new Vector2(1, 1); Vector2 offset = new Vector2(0, 0); float s = 0.0f; if (currentResolutionOverride != null) { switch (currentResolutionOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = pixelHeight / nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = pixelWidth / nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit: float nativeAspect = (float)nativeResolutionWidth / nativeResolutionHeight; float currentAspect = pixelWidth / pixelHeight; if (currentAspect < nativeAspect) s = pixelWidth / nativeResolutionWidth; else s = pixelHeight / nativeResolutionHeight; if (currentResolutionOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit) { if (s > 1.0f) s = Mathf.Floor(s); // round number else s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(pixelWidth / nativeResolutionWidth, pixelHeight / nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentResolutionOverride.scale; scale.Set(s, s); break; } scale *= zoomScale; // no offset when ScaleToFit if (currentResolutionOverride.autoScaleMode != tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { switch (currentResolutionOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: offset = new Vector2(Mathf.Round((nativeResolutionWidth * scale.x - pixelWidth ) / 2.0f), Mathf.Round((nativeResolutionHeight * scale.y - pixelHeight) / 2.0f)); break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentResolutionOverride.offsetPixels; break; } } } float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (viewportClippingEnabled) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)viewportRegion.x, (int)viewportRegion.y, (int)viewportRegion.z, (int)viewportRegion.w); float viewportLeft = sr.x / vw; float viewportBottom = sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; Rect r = new Rect( viewportLeft, viewportBottom, viewportWidth, viewportHeight ); if (mainCamera.rect.x != viewportLeft || mainCamera.rect.y != viewportBottom || mainCamera.rect.width != viewportWidth || mainCamera.rect.height != viewportHeight) { mainCamera.rect = r; } float maxWidth = Mathf.Min( 1.0f - r.x, r.width ); float maxHeight = Mathf.Min( 1.0f - r.y, r.height ); float rectOffsetX = sr.x * scale.x; float rectOffsetY = sr.y * scale.y; if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { mainCamera.rect = new Rect(0, 0, 1, 1); } _screenExtents.Set(left / scale.x, top / scale.y, (right - left) / scale.x, (bottom - top) / scale.y); float far = mainCamera.farClipPlane; float near = mainCamera.near; // set up externally used variables orthoSize = (top - bottom) / 2.0f; _scaledResolution = new Vector2((right - left) / scale.x, (top - bottom) / scale.y); _screenOffset = offset; // Additional half texel offset // Takes care of texture unit offset, if necessary. // should be off on all opengl platforms // and on on PC/D3D bool halfTexelOffset = false; halfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexelOffsetAmount = (halfTexelOffset)?1.0f:0.0f; float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left + halfTexelOffsetAmount) / (right - left); float b = -(bottom + top - halfTexelOffsetAmount) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a; m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b; m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c; m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1; mainCamera.projectionMatrix = m; }
void Start() { //Debug.Log("EnemyPlaneController:Start() - direction = " + direction); objCamera = (tk2dCamera) GameObject.FindWithTag("MainCamera").GetComponent<tk2dCamera>(); objSprite = GetComponent<tk2dAnimatedSprite>(); trans = transform; health = maxHealth; trailTrans = transform.root.Find("TrailPosition"); launcherTrans = transform.root.Find("LauncherPosition"); parTrail = (GameObject)Instantiate(parVaporTrail, trailTrans.position, Quaternion.identity); if (direction == PlaneDirection.RIGHT) { objSprite.FlipX(); } }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// Or however the override is set up. /// </summary> public void UpdateCameraMatrix() { Upgrade(); if (!this.viewportClippingEnabled) inst = this; Camera unityCamera = UnityCamera; tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (unityCamera.rect != cameraSettings.rect) unityCamera.rect = cameraSettings.rect; // Projection type is inherited from base camera _targetResolution = GetScreenPixelDimensions(settings); if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { if (unityCamera.orthographic == true) unityCamera.orthographic = false; float fov = Mathf.Min(179.9f, inheritedCameraSettings.fieldOfView / Mathf.Max(0.001f, ZoomFactor)); if (unityCamera.fieldOfView != fov) unityCamera.fieldOfView = fov; _screenExtents.Set( -unityCamera.aspect, -1, unityCamera.aspect * 2, 2 ); _nativeScreenExtents = _screenExtents; unityCamera.ResetProjectionMatrix(); } else { if (unityCamera.orthographic == false) unityCamera.orthographic = true; // Find an override if necessary Matrix4x4 m = GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents ); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_1) // Windows phone? if (Application.platform == RuntimePlatform.WP8Player && (Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)) { float angle = (Screen.orientation == ScreenOrientation.LandscapeRight) ? 90.0f : -90.0f; Matrix4x4 m2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); m = m2 * m; } #endif if (unityCamera.projectionMatrix != m) { unityCamera.projectionMatrix = m; } } }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// </summary> public void UpdateCameraMatrix() { inst = this; if (!mainCamera.orthographic) { // Must be orthographic Debug.LogError("tk2dCamera must be orthographic"); mainCamera.orthographic = true; } float pixelWidth = mainCamera.pixelWidth; float pixelHeight = mainCamera.pixelHeight; #if UNITY_EDITOR if (forceResolutionInEditor) { pixelWidth = forceResolution.x; pixelHeight = forceResolution.y; } #endif _targetResolution = new Vector2(pixelWidth, pixelHeight); // Find an override if necessary if (!enableResolutionOverrides) { currentResolutionOverride = null; } if (enableResolutionOverrides && (currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (resolutionOverride != null) { foreach (var ovr in resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } Vector2 scale = new Vector2(1, 1); Vector2 offset = new Vector2(0, 0); float s = 0.0f; if (currentResolutionOverride != null) { switch (currentResolutionOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = pixelHeight / nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = pixelWidth / nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: float nativeAspect = (float)nativeResolutionWidth / nativeResolutionHeight; float currentAspect = pixelWidth / pixelHeight; if (currentAspect < nativeAspect) { s = pixelWidth / nativeResolutionWidth; } else { s = pixelHeight / nativeResolutionHeight; } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(pixelWidth / nativeResolutionWidth, pixelHeight / nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentResolutionOverride.scale; scale.Set(s, s); break; } // no offset when ScaleToFit if (currentResolutionOverride.autoScaleMode != tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { switch (currentResolutionOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: offset = new Vector2(Mathf.Round((nativeResolutionWidth * scale.x - pixelWidth) / 2.0f), Mathf.Round((nativeResolutionHeight * scale.y - pixelHeight) / 2.0f)); break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentResolutionOverride.offsetPixels; break; } } } float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; _screenExtents.Set(left / scale.x, top / scale.y, (right - left) / scale.x, (bottom - top) / scale.y); float far = mainCamera.farClipPlane; float near = mainCamera.near; // set up externally used variables orthoSize = (top - bottom) / 2.0f; _scaledResolution = new Vector2(right / scale.x, top / scale.y); _screenOffset = offset; // Additional half texel offset // Takes care of texture unit offset, if necessary. // should be off on all opengl platforms // and on on PC/D3D bool halfTexelOffset = false; halfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexelOffsetAmount = (halfTexelOffset)?1.0f:0.0f; float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left + halfTexelOffsetAmount) / (right - left); float b = -(bottom + top - halfTexelOffsetAmount) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0, 0] = x; m[0, 1] = 0; m[0, 2] = 0; m[0, 3] = a; m[1, 0] = 0; m[1, 1] = y; m[1, 2] = 0; m[1, 3] = b; m[2, 0] = 0; m[2, 1] = 0; m[2, 2] = z; m[2, 3] = c; m[3, 0] = 0; m[3, 1] = 0; m[3, 2] = 0; m[3, 3] = 1; mainCamera.projectionMatrix = m; }
// Use this for initialization void Awake() { tkCam = GetComponent<tk2dCamera>(); }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// Or however the override is set up. /// </summary> public void UpdateCameraMatrix() { Upgrade(); if (!this.viewportClippingEnabled) { inst = this; } Camera unityCamera = UnityCamera; tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (unityCamera.clearFlags != cameraSettings.clearFlags) { unityCamera.clearFlags = cameraSettings.clearFlags; } if (unityCamera.backgroundColor != cameraSettings.backgroundColor) { unityCamera.backgroundColor = cameraSettings.backgroundColor; } if (unityCamera.cullingMask != cameraSettings.cullingMask) { unityCamera.cullingMask = cameraSettings.cullingMask; } if (unityCamera.farClipPlane != cameraSettings.farClipPlane) { unityCamera.farClipPlane = cameraSettings.farClipPlane; } if (unityCamera.nearClipPlane != cameraSettings.nearClipPlane) { unityCamera.nearClipPlane = cameraSettings.nearClipPlane; } if (unityCamera.rect != cameraSettings.rect) { unityCamera.rect = cameraSettings.rect; } if (unityCamera.depth != cameraSettings.depth) { unityCamera.depth = cameraSettings.depth; } if (unityCamera.renderingPath != cameraSettings.renderingPath) { unityCamera.renderingPath = cameraSettings.renderingPath; } // Checking unityCamera.targetTexture allocates memory. Simply setting it all the time now. unityCamera.targetTexture = cameraSettings.targetTexture; if (unityCamera.hdr != cameraSettings.hdr) { unityCamera.hdr = cameraSettings.hdr; } // Projection type is inherited from base camera _targetResolution = GetScreenPixelDimensions(settings); if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { unityCamera.orthographic = false; unityCamera.fieldOfView = inheritedCameraSettings.fieldOfView * ZoomFactor; unityCamera.transparencySortMode = inheritedCameraSettings.transparencySortMode; _screenExtents.Set(-unityCamera.aspect, -1, unityCamera.aspect * 2, 2); _nativeScreenExtents = _screenExtents; unityCamera.ResetProjectionMatrix(); } else { unityCamera.transparencySortMode = TransparencySortMode.Orthographic; unityCamera.orthographic = true; // Find an override if necessary Matrix4x4 m = GetProjectionMatrixForOverride(settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_1) // Windows phone? if (Application.platform == RuntimePlatform.WP8Player && (Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)) { float angle = (Screen.orientation == ScreenOrientation.LandscapeRight) ? 90.0f : -90.0f; Matrix4x4 m2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); m = m2 * m; } #endif if (unityCamera.projectionMatrix != m) { unityCamera.projectionMatrix = m; } } }
Matrix4x4 GetProjectionMatrixForOverride( tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float pixelWidth, float pixelHeight, bool halfTexelOffset, out Rect screenExtents, out Rect unscaledScreenExtents ) { Vector2 scale = GetScaleForOverride( settings, currentOverride, pixelWidth, pixelHeight ); Vector2 offset = GetOffsetForOverride( settings, currentOverride, scale, pixelWidth, pixelHeight); float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; Vector2 nativeResolutionOffset = Vector2.zero; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (this.viewportClippingEnabled && this.InheritConfig != null) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)this.viewportRegion.x, (int)this.viewportRegion.y, (int)this.viewportRegion.z, (int)this.viewportRegion.w); float viewportLeft = -offset.x / pixelWidth + sr.x / vw; float viewportBottom = -offset.y / pixelHeight + sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; Rect r = new Rect( viewportLeft, viewportBottom, viewportWidth, viewportHeight ); if (UnityCamera.rect.x != viewportLeft || UnityCamera.rect.y != viewportBottom || UnityCamera.rect.width != viewportWidth || UnityCamera.rect.height != viewportHeight) { UnityCamera.rect = r; } float maxWidth = Mathf.Min( 1.0f - r.x, r.width ); float maxHeight = Mathf.Min( 1.0f - r.y, r.height ); float rectOffsetX = sr.x * scale.x - offset.x; float rectOffsetY = sr.y * scale.y - offset.y; if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { if (UnityCamera.rect != CameraSettings.rect) { UnityCamera.rect = CameraSettings.rect; } } // By default the camera is orthographic, bottom left, 1 pixel per meter if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { float w = (right - left) * 0.5f; left -= w; right -= w; float h = (top - bottom) * 0.5f; top -= h; bottom -= h; nativeResolutionOffset.Set(-nativeResolutionWidth / 2.0f, -nativeResolutionHeight / 2.0f); } float orthoSize = settings.cameraSettings.orthographicSize; switch (settings.cameraSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: orthoSize = 2.0f * settings.cameraSettings.orthographicSize / settings.nativeResolutionHeight; break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: orthoSize = 1.0f / settings.cameraSettings.orthographicPixelsPerMeter; break; } float zoomScale = 1.0f / ZoomFactor; // Only need the half texel offset on PC/D3D bool needHalfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexel = (halfTexelOffset && needHalfTexelOffset) ? 0.5f : 0.0f; float s = orthoSize * zoomScale; screenExtents = new Rect(left * s / scale.x, bottom * s / scale.y, (right - left) * s / scale.x, (top - bottom) * s / scale.y); unscaledScreenExtents = new Rect(nativeResolutionOffset.x * s, nativeResolutionOffset.y * s, nativeResolutionWidth * s, nativeResolutionHeight * s); // Near and far clip planes are tweakable per camera, so we pull from current camera instance regardless of inherited values return OrthoOffCenter(scale, orthoSize * (left + halfTexel) * zoomScale, orthoSize * (right + halfTexel) * zoomScale, orthoSize * (bottom - halfTexel) * zoomScale, orthoSize * (top - halfTexel) * zoomScale, UnityCamera.nearClipPlane, UnityCamera.farClipPlane); }
public override void OnInspectorGUI() { //DrawDefaultInspector(); tk2dCamera _target = (tk2dCamera)target; var frameBorderStyle = EditorStyles.textField; // sanity if (_target.resolutionOverride == null) { _target.resolutionOverride = new tk2dCameraResolutionOverride[0]; GUI.changed = true; } bool cameraOverrideChanged = false; _target.inheritSettings = EditorGUILayout.ObjectField("Inherit settings", _target.inheritSettings, typeof(tk2dCamera), true) as tk2dCamera; if (_target.inheritSettings != null) { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); if (GUILayout.Button("Clear")) { _target.inheritSettings = null; GUI.changed = true; } GUILayout.EndHorizontal(); GUILayout.Space(32); } else { GUILayout.Space(8); _target.enableResolutionOverrides = EditorGUILayout.Toggle("Resolution overrides", _target.enableResolutionOverrides); if (_target.enableResolutionOverrides) { EditorGUILayout.LabelField("Native resolution", EditorStyles.boldLabel); EditorGUI.indentLevel++; _target.nativeResolutionWidth = EditorGUILayout.IntField("Width", _target.nativeResolutionWidth); _target.nativeResolutionHeight = EditorGUILayout.IntField("Height", _target.nativeResolutionHeight); EditorGUI.indentLevel--; // Overrides EditorGUILayout.LabelField("Overrides", EditorStyles.boldLabel); EditorGUI.indentLevel++; int deleteId = -1; for (int i = 0; i < _target.resolutionOverride.Length; ++i) { var ovr = _target.resolutionOverride[i]; EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(8); ovr.name = EditorGUILayout.TextField("Name", ovr.name); int resolutionMatch = (ovr.width == -1 && ovr.height == -1) ? 0 : 1; int newResolutionMatch = EditorGUILayout.Popup("Match resolution", resolutionMatch, new string[] { "Wildcard (Match-all)", "Explicit" }); if (resolutionMatch != newResolutionMatch) { if (newResolutionMatch == 0) { ovr.width = -1; ovr.height = -1; } else { ovr.width = 1024; ovr.height = 768; } resolutionMatch = newResolutionMatch; EditorUtility.SetDirty(_target); } EditorGUI.indentLevel++; if (resolutionMatch != 0) { ovr.width = EditorGUILayout.IntField("Width", ovr.width); ovr.height = EditorGUILayout.IntField("Height", ovr.height); } EditorGUI.indentLevel--; ovr.autoScaleMode = (tk2dCameraResolutionOverride.AutoScaleMode)EditorGUILayout.EnumPopup("Auto Scale", ovr.autoScaleMode); if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.None) { EditorGUI.indentLevel++; ovr.scale = EditorGUILayout.FloatField("Scale", ovr.scale); EditorGUI.indentLevel--; } if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { string msg = "The native resolution image will be stretched to fit the target display. " + "Image quality will suffer if non-uniform scaling occurs."; tk2dGuiUtility.InfoBox(msg, tk2dGuiUtility.WarningLevel.Info); } else { ovr.fitMode = (tk2dCameraResolutionOverride.FitMode)EditorGUILayout.EnumPopup("Fit Mode", ovr.fitMode); if (ovr.fitMode == tk2dCameraResolutionOverride.FitMode.Constant) { EditorGUI.indentLevel++; ovr.offsetPixels.x = EditorGUILayout.FloatField("X", ovr.offsetPixels.x); ovr.offsetPixels.y = EditorGUILayout.FloatField("Y", ovr.offsetPixels.y); EditorGUI.indentLevel--; } } GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); if (GUILayout.Button("Delete", EditorStyles.miniButton)) { deleteId = i; } GUILayout.EndHorizontal(); GUILayout.Space(4); EditorGUILayout.EndVertical(); } if (deleteId != -1) { List <tk2dCameraResolutionOverride> ovr = new List <tk2dCameraResolutionOverride>(_target.resolutionOverride); ovr.RemoveAt(deleteId); _target.resolutionOverride = ovr.ToArray(); GUI.changed = true; Repaint(); } EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(32); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add override", GUILayout.ExpandWidth(false))) { tk2dCameraResolutionOverride ovr = new tk2dCameraResolutionOverride(); ovr.name = "Wildcard Override"; ovr.width = -1; ovr.height = -1; ovr.autoScaleMode = tk2dCameraResolutionOverride.AutoScaleMode.FitVisible; ovr.fitMode = tk2dCameraResolutionOverride.FitMode.Center; System.Array.Resize(ref _target.resolutionOverride, _target.resolutionOverride.Length + 1); _target.resolutionOverride[_target.resolutionOverride.Length - 1] = ovr; GUI.changed = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(32); EditorGUILayout.EndVertical(); EditorGUI.indentLevel--; } EditorGUILayout.Space(); EditorGUILayout.LabelField("Camera resolution", EditorStyles.boldLabel); GUIContent toggleLabel = new GUIContent("Force Editor Resolution", "When enabled, forces the resolution in the editor regardless of the size of the game window."); EditorGUI.indentLevel++; tk2dGuiUtility.BeginChangeCheck(); _target.forceResolutionInEditor = EditorGUILayout.Toggle(toggleLabel, _target.forceResolutionInEditor); if (tk2dGuiUtility.EndChangeCheck()) { cameraOverrideChanged = true; } if (_target.forceResolutionInEditor) { tk2dGuiUtility.BeginChangeCheck(); int selectedResolution = EditorGUILayout.Popup("Preset", 0, presetListStr); if (selectedResolution != 0) { var preset = presets[selectedResolution - 1]; _target.forceResolution.x = preset.width; _target.forceResolution.y = preset.height; GUI.changed = true; } _target.forceResolution.x = EditorGUILayout.IntField("Width", (int)_target.forceResolution.x); _target.forceResolution.y = EditorGUILayout.IntField("Height", (int)_target.forceResolution.y); // clamp to a sensible value _target.forceResolution.x = Mathf.Max(_target.forceResolution.x, 50); _target.forceResolution.y = Mathf.Max(_target.forceResolution.y, 50); Rect r = GUILayoutUtility.GetRect(1, 1, GUILayout.ExpandWidth(true), GUILayout.MinHeight(43)); EditorGUI.HelpBox(new Rect(r.x + 4, r.y, r.width - 8, r.height), "Ensure that the the game view resolution is the same as the override chosen here, otherwise the game window will not display correctly.", MessageType.Warning); if (tk2dGuiUtility.EndChangeCheck()) { cameraOverrideChanged = true; } } else { EditorGUILayout.FloatField("Width", _target.TargetResolution.x); EditorGUILayout.FloatField("Height", _target.TargetResolution.y); } EditorGUI.indentLevel--; } EditorGUILayout.LabelField("Viewport Clipping", EditorStyles.boldLabel); EditorGUI.indentLevel++; _target.viewportClippingEnabled = EditorGUILayout.Toggle("Enable", _target.viewportClippingEnabled); if (_target.viewportClippingEnabled) { _target.screenCamera = EditorGUILayout.ObjectField("Screen Camera", _target.screenCamera, typeof(Camera), true) as Camera; if (_target.screenCamera == null) { tk2dGuiUtility.InfoBox("Viewport Clipping disabled.\nAttach a link to a camera which displays the entire screen to enable viewport clipping.", tk2dGuiUtility.WarningLevel.Error); } else if (_target.screenCamera.rect != new Rect(0, 0, 1, 1)) { tk2dGuiUtility.InfoBox("Viewport Clipping disabled.\nLinked camera can't have a viewport set.", tk2dGuiUtility.WarningLevel.Error); } else { EditorGUILayout.LabelField("Region"); EditorGUI.indentLevel++; _target.viewportRegion.x = EditorGUILayout.IntField("X", (int)_target.viewportRegion.x); _target.viewportRegion.y = EditorGUILayout.IntField("Y", (int)_target.viewportRegion.y); _target.viewportRegion.z = EditorGUILayout.IntField("Width", (int)_target.viewportRegion.z); _target.viewportRegion.w = EditorGUILayout.IntField("Height", (int)_target.viewportRegion.w); EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; if (cameraOverrideChanged) { // Propagate values to all tk2dCameras in scene tk2dCamera[] otherCameras = Resources.FindObjectsOfTypeAll(typeof(tk2dCamera)) as tk2dCamera[]; foreach (tk2dCamera thisCamera in otherCameras) { thisCamera.forceResolutionInEditor = _target.forceResolutionInEditor; thisCamera.forceResolution = _target.forceResolution; thisCamera.UpdateCameraMatrix(); } // Update all anchors after that tk2dCameraAnchor[] anchors = Resources.FindObjectsOfTypeAll(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var anchor in anchors) { anchor.ForceUpdateTransform(); } } if (GUI.changed) { EditorUtility.SetDirty(target); tk2dCameraAnchor[] allAlignmentObjects = GameObject.FindObjectsOfType(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var v in allAlignmentObjects) { EditorUtility.SetDirty(v); } } GUILayout.Space(16.0f); EditorGUILayout.LabelField("Tools", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("Create Anchor", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { tk2dCamera cam = (tk2dCamera)target; GameObject go = new GameObject("Anchor"); go.transform.parent = cam.transform; tk2dCameraAnchor cameraAnchor = go.AddComponent <tk2dCameraAnchor>(); cameraAnchor.tk2dCamera = cam; EditorGUIUtility.PingObject(go); } EditorGUILayout.EndHorizontal(); // { // tk2dCamera cam = (tk2dCamera)target; // cam.zoomScale = EditorGUILayout.FloatField("Zoom scale", cam.zoomScale); // } }
void Start() { objCamera = (tk2dCamera)GameObject.FindWithTag("MainCamera").GetComponent <tk2dCamera>(); ptrScriptVariable = (EnemyVariables)GetComponent(typeof(EnemyVariables)); }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// </summary> public void UpdateCameraMatrix() { if (!this.viewportClippingEnabled) { inst = this; } if (!mainCamera.orthographic) { // Must be orthographic Debug.LogError("tk2dCamera must be orthographic"); mainCamera.orthographic = true; } tk2dCamera settings = Settings; bool viewportClippingEnabled = this.viewportClippingEnabled && this.screenCamera != null && this.screenCamera.rect == unitRect; Camera screenCamera = viewportClippingEnabled ? this.screenCamera : mainCamera; float pixelWidth = screenCamera.pixelWidth; float pixelHeight = screenCamera.pixelHeight; #if UNITY_EDITOR if (settings.forceResolutionInEditor) { pixelWidth = settings.forceResolution.x; pixelHeight = settings.forceResolution.y; } #endif _targetResolution = new Vector2(pixelWidth, pixelHeight); // Find an override if necessary if (!settings.enableResolutionOverrides) { currentResolutionOverride = null; } if (settings.enableResolutionOverrides && (currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (settings.resolutionOverride != null) { foreach (var ovr in settings.resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } Vector2 scale = new Vector2(1, 1); Vector2 offset = new Vector2(0, 0); float s = 0.0f; if (currentResolutionOverride != null) { switch (currentResolutionOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = pixelHeight / settings.nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = pixelWidth / settings.nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit: float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight; float currentAspect = pixelWidth / pixelHeight; if (currentAspect < nativeAspect) { s = pixelWidth / settings.nativeResolutionWidth; } else { s = pixelHeight / settings.nativeResolutionHeight; } if (currentResolutionOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfectFit) { if (s > 1.0f) { s = Mathf.Floor(s); // round number } else { s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(pixelWidth / settings.nativeResolutionWidth, pixelHeight / settings.nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentResolutionOverride.scale; scale.Set(s, s); break; } scale *= zoomScale; // no offset when ScaleToFit if (currentResolutionOverride.autoScaleMode != tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { switch (currentResolutionOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: offset = new Vector2(Mathf.Round((settings.nativeResolutionWidth * scale.x - pixelWidth) / 2.0f), Mathf.Round((settings.nativeResolutionHeight * scale.y - pixelHeight) / 2.0f)); break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentResolutionOverride.offsetPixels; break; } } } float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (viewportClippingEnabled) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)viewportRegion.x, (int)viewportRegion.y, (int)viewportRegion.z, (int)viewportRegion.w); float viewportLeft = -offset.x / pixelWidth + sr.x / vw; float viewportBottom = -offset.y / pixelHeight + sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; Rect r = new Rect(viewportLeft, viewportBottom, viewportWidth, viewportHeight); if (mainCamera.rect.x != viewportLeft || mainCamera.rect.y != viewportBottom || mainCamera.rect.width != viewportWidth || mainCamera.rect.height != viewportHeight) { mainCamera.rect = r; } float maxWidth = Mathf.Min(1.0f - r.x, r.width); float maxHeight = Mathf.Min(1.0f - r.y, r.height); float rectOffsetX = sr.x * scale.x - offset.x; float rectOffsetY = sr.y * scale.y - offset.y; if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { mainCamera.rect = new Rect(0, 0, 1, 1); } _screenExtents.Set(left / scale.x, top / scale.y, (right - left) / scale.x, (bottom - top) / scale.y); float far = mainCamera.farClipPlane; float near = mainCamera.near; // set up externally used variables orthoSize = (top - bottom) / 2.0f; _scaledResolution = new Vector2((right - left) / scale.x, (top - bottom) / scale.y); _screenOffset = offset; // Additional half texel offset // Takes care of texture unit offset, if necessary. // should be off on all opengl platforms // and on on PC/D3D bool halfTexelOffset = false; halfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexelOffsetAmount = (halfTexelOffset)?1.0f:0.0f; float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left + halfTexelOffsetAmount) / (right - left); float b = -(bottom + top - halfTexelOffsetAmount) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0, 0] = x; m[0, 1] = 0; m[0, 2] = 0; m[0, 3] = a; m[1, 0] = 0; m[1, 1] = y; m[1, 2] = 0; m[1, 3] = b; m[2, 0] = 0; m[2, 1] = 0; m[2, 2] = z; m[2, 3] = c; m[3, 0] = 0; m[3, 1] = 0; m[3, 2] = 0; m[3, 3] = 1; mainCamera.projectionMatrix = m; }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// Or however the override is set up. /// </summary> public void UpdateCameraMatrix() { Upgrade(); if (!this.viewportClippingEnabled) { inst = this; } Camera unityCamera = UnityCamera; tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (unityCamera.rect != cameraSettings.rect) { unityCamera.rect = cameraSettings.rect; } // Projection type is inherited from base camera _targetResolution = GetScreenPixelDimensions(settings); if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { if (unityCamera.orthographic == true) { unityCamera.orthographic = false; } float fov = Mathf.Min(179.9f, inheritedCameraSettings.fieldOfView / Mathf.Max(0.001f, ZoomFactor)); if (unityCamera.fieldOfView != fov) { unityCamera.fieldOfView = fov; } _screenExtents.Set(-unityCamera.aspect, -1, unityCamera.aspect * 2, 2); _nativeScreenExtents = _screenExtents; unityCamera.ResetProjectionMatrix(); } else { if (unityCamera.orthographic == false) { unityCamera.orthographic = true; } // Find an override if necessary Matrix4x4 m = GetProjectionMatrixForOverride(settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_1) // Windows phone? if (Application.platform == RuntimePlatform.WP8Player && (Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)) { float angle = (Screen.orientation == ScreenOrientation.LandscapeRight) ? 90.0f : -90.0f; Matrix4x4 m2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); m = m2 * m; } #endif if (unityCamera.projectionMatrix != m) { unityCamera.projectionMatrix = m; } } }
void DrawEditorGUI() { if (GUILayout.Button("Commit")) { // Select all children, EXCLUDING self Transform[] allTransforms = batcher.transform.GetComponentsInChildren <Transform>(); allTransforms = (from t in allTransforms where t != batcher.transform select t).ToArray(); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) Renderer[] allRenderers = batcher.transform.GetComponentsInChildren <Renderer>(); allRenderers = (from r in allRenderers where r != batcher.GetComponent <Renderer>() select r).ToArray(); if (allRenderers.Length > 0) { string sortingLayerName = allRenderers[0].sortingLayerName; int sortingOrder = allRenderers[0].sortingOrder; foreach (Renderer r in allRenderers) { if (sortingLayerName != r.sortingLayerName || sortingOrder != r.sortingOrder) { EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: Child objects use different sorting layer names and/or sorting orders.\n\nOnly one sorting layer and order is permitted in a static sprite batcher.", "Ok"); return; } } } #endif // sort sprites, smaller to larger z if (batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.SortToCamera)) { tk2dCamera tk2dCam = tk2dCamera.CameraForLayer(batcher.gameObject.layer); Camera cam = tk2dCam ? tk2dCam.GetComponent <Camera>() : Camera.main; allTransforms = (from t in allTransforms orderby cam.WorldToScreenPoint((t.GetComponent <Renderer>() != null) ? t.GetComponent <Renderer>().bounds.center : t.position).z descending select t).ToArray(); } else { allTransforms = (from t in allTransforms orderby((t.GetComponent <Renderer>() != null) ? t.GetComponent <Renderer>().bounds.center : t.position).z descending select t).ToArray(); } // and within the z sort by material if (allTransforms.Length == 0) { EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: No child objects found", "Ok"); return; } #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) MeshCollider[] childMeshColliders = GetComponentsInChildrenExcludeSelf <MeshCollider>(batcher.transform); BoxCollider[] childBoxColliders = GetComponentsInChildrenExcludeSelf <BoxCollider>(batcher.transform); BoxCollider2D[] childBoxCollider2Ds = GetComponentsInChildrenExcludeSelf <BoxCollider2D>(batcher.transform); EdgeCollider2D[] childEdgeCollider2Ds = GetComponentsInChildrenExcludeSelf <EdgeCollider2D>(batcher.transform); PolygonCollider2D[] childPolygonCollider2Ds = GetComponentsInChildrenExcludeSelf <PolygonCollider2D>(batcher.transform); if ((childMeshColliders.Length > 0 || childBoxColliders.Length > 0) && (childBoxCollider2Ds.Length > 0 || childEdgeCollider2Ds.Length > 0 || childPolygonCollider2Ds.Length > 0)) { EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: Can't mix 2D and 3D colliders", "Ok"); return; } #endif Dictionary <Transform, int> batchedSpriteLookup = new Dictionary <Transform, int>(); batchedSpriteLookup[batcher.transform] = -1; Matrix4x4 batcherWorldToLocal = batcher.transform.worldToLocalMatrix; batcher.spriteCollection = null; batcher.batchedSprites = new tk2dBatchedSprite[allTransforms.Length]; List <tk2dTextMeshData> allTextMeshData = new List <tk2dTextMeshData>(); int currBatchedSprite = 0; foreach (var t in allTransforms) { tk2dBaseSprite baseSprite = t.GetComponent <tk2dBaseSprite>(); tk2dTextMesh textmesh = t.GetComponent <tk2dTextMesh>(); tk2dBatchedSprite bs = new tk2dBatchedSprite(); bs.name = t.gameObject.name; bs.position = t.localPosition; bs.rotation = t.localRotation; bs.relativeMatrix = batcherWorldToLocal * t.localToWorldMatrix; if (baseSprite) { bs.baseScale = Vector3.one; bs.localScale = new Vector3(t.localScale.x * baseSprite.scale.x, t.localScale.y * baseSprite.scale.y, t.localScale.z * baseSprite.scale.z); FillBatchedSprite(bs, t.gameObject); // temp redundant - just incase batcher expects to point to a valid one, somewhere we've missed batcher.spriteCollection = baseSprite.Collection; } else if (textmesh) { bs.spriteCollection = null; bs.type = tk2dBatchedSprite.Type.TextMesh; bs.color = textmesh.color; bs.baseScale = textmesh.scale; bs.renderLayer = textmesh.SortingOrder; bs.localScale = new Vector3(t.localScale.x * textmesh.scale.x, t.localScale.y * textmesh.scale.y, t.localScale.z * textmesh.scale.z); bs.FormattedText = textmesh.FormattedText; tk2dTextMeshData tmd = new tk2dTextMeshData(); tmd.font = textmesh.font; tmd.text = textmesh.text; tmd.color = textmesh.color; tmd.color2 = textmesh.color2; tmd.useGradient = textmesh.useGradient; tmd.textureGradient = textmesh.textureGradient; tmd.anchor = textmesh.anchor; tmd.kerning = textmesh.kerning; tmd.maxChars = textmesh.maxChars; tmd.inlineStyling = textmesh.inlineStyling; tmd.formatting = textmesh.formatting; tmd.wordWrapWidth = textmesh.wordWrapWidth; tmd.spacing = textmesh.Spacing; tmd.lineSpacing = textmesh.LineSpacing; bs.xRefId = allTextMeshData.Count; allTextMeshData.Add(tmd); } else { // Empty GameObject bs.spriteId = -1; bs.baseScale = Vector3.one; bs.localScale = t.localScale; bs.type = tk2dBatchedSprite.Type.EmptyGameObject; } batchedSpriteLookup[t] = currBatchedSprite; batcher.batchedSprites[currBatchedSprite++] = bs; } batcher.allTextMeshData = allTextMeshData.ToArray(); int idx = 0; foreach (var t in allTransforms) { var bs = batcher.batchedSprites[idx]; bs.parentId = batchedSpriteLookup[t.parent]; t.parent = batcher.transform; // unparent ++idx; } Transform[] directChildren = (from t in allTransforms where t.parent == batcher.transform select t).ToArray(); foreach (var t in directChildren) { GameObject.DestroyImmediate(t.gameObject); } Vector3 inverseScale = new Vector3(1.0f / batcher.scale.x, 1.0f / batcher.scale.y, 1.0f / batcher.scale.z); batcher.transform.localScale = Vector3.Scale(batcher.transform.localScale, inverseScale); batcher.Build(); EditorUtility.SetDirty(target); } }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// Or however the override is set up. /// </summary> public void UpdateCameraMatrix() { Upgrade(); if (!this.viewportClippingEnabled) { inst = this; } Camera unityCamera = UnityCamera; tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (unityCamera.clearFlags != cameraSettings.clearFlags) { unityCamera.clearFlags = cameraSettings.clearFlags; } if (unityCamera.backgroundColor != cameraSettings.backgroundColor) { unityCamera.backgroundColor = cameraSettings.backgroundColor; } if (unityCamera.cullingMask != cameraSettings.cullingMask) { unityCamera.cullingMask = cameraSettings.cullingMask; } if (unityCamera.farClipPlane != cameraSettings.farClipPlane) { unityCamera.farClipPlane = cameraSettings.farClipPlane; } if (unityCamera.nearClipPlane != cameraSettings.nearClipPlane) { unityCamera.nearClipPlane = cameraSettings.nearClipPlane; } if (unityCamera.rect != cameraSettings.rect) { unityCamera.rect = cameraSettings.rect; } if (unityCamera.depth != cameraSettings.depth) { unityCamera.depth = cameraSettings.depth; } if (unityCamera.renderingPath != cameraSettings.renderingPath) { unityCamera.renderingPath = cameraSettings.renderingPath; } // Checking unityCamera.targetTexture allocates memory. Simply setting it all the time now. unityCamera.targetTexture = cameraSettings.targetTexture; if (unityCamera.hdr != cameraSettings.hdr) { unityCamera.hdr = cameraSettings.hdr; } // Projection type is inherited from base camera _targetResolution = GetScreenPixelDimensions(settings); if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { unityCamera.orthographic = false; unityCamera.fieldOfView = inheritedCameraSettings.fieldOfView * ZoomFactor; unityCamera.transparencySortMode = inheritedCameraSettings.transparencySortMode; _screenExtents.Set(-unityCamera.aspect, -1, unityCamera.aspect * 2, 2); _nativeScreenExtents = _screenExtents; unityCamera.ResetProjectionMatrix(); } else { unityCamera.transparencySortMode = TransparencySortMode.Orthographic; unityCamera.orthographic = true; // Find an override if necessary Matrix4x4 m = GetProjectionMatrixForOverride(settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents); if (unityCamera.projectionMatrix != m) { unityCamera.projectionMatrix = m; } } }
/// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// </summary> public void UpdateCameraMatrix() { inst = this; float pixelWidth = mainCamera.pixelWidth; float pixelHeight = mainCamera.pixelHeight; #if UNITY_EDITOR if (forceResolutionInEditor) { pixelWidth = forceResolution.x; pixelHeight = forceResolution.y; } #endif // Find an override if necessary if (currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) ) { currentResolutionOverride = null; // find one if it matches the current resolution if (resolutionOverride != null) { foreach (var ovr in resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } float scale = (currentResolutionOverride != null)?currentResolutionOverride.scale:1.0f; float left = 0.0f, top = 0.0f; float right = pixelWidth, bottom = pixelHeight; float far = mainCamera.farClipPlane; float near = mainCamera.near; // set up externally used variables orthoSize = (bottom - top) / 2.0f; resolution = new Vector2(right / scale, bottom / scale); // Additional half texel offset // Takes care of texture unit offset, if necessary. // should be off on all opengl platforms // and on on PC/D3D bool halfTexelOffset = false; halfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexelOffsetAmount = (halfTexelOffset)?1.0f:0.0f; float x = (2.0f) / (right - left) * scale; float y = (2.0f) / (bottom - top) * scale; float z = -2.0f / (far - near); float a = -(right + left + halfTexelOffsetAmount) / (right - left); float b = -(top + bottom - halfTexelOffsetAmount) / (bottom - top); float c = -(2.0f * far * near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0, 0] = x; m[0, 1] = 0; m[0, 2] = 0; m[0, 3] = a; m[1, 0] = 0; m[1, 1] = y; m[1, 2] = 0; m[1, 3] = b; m[2, 0] = 0; m[2, 1] = 0; m[2, 2] = z; m[2, 3] = c; m[3, 0] = 0; m[3, 1] = 0; m[3, 2] = 0; m[3, 3] = 1; mainCamera.projectionMatrix = m; }
void Awake() { _instance = this; _transform = transform; if (GameCamera == null) GameCamera = GetComponent<Camera>(); if (GameCamera == null) Debug.LogError("Unity Camera not set and not found on the GameObject: " + gameObject.name); #if PC2D_TK2D_SUPPORT Tk2dCam = GetComponent<tk2dCamera>(); #endif // Reset the axis functions ResetAxisFunctions(); // Remove empty targets for (int i = 0; i < CameraTargets.Count; i++) { if (CameraTargets[i].TargetTransform == null) { CameraTargets.RemoveAt(i); } } ScreenSizeInWorldCoordinates = _startScreenSizeInWorldCoordinates = Utils.GetScreenSizeInWorldCoords(GameCamera, Mathf.Abs(Vector3D(_transform.localPosition))); _cameraDepthPos = Vector3D(_transform.localPosition); _originalCameraDepthSign = Mathf.Sign(_cameraDepthPos); // Center on target if (CenterTargetOnStart && CameraTargets.Count > 0) { var targetsMidPoint = GetTargetsWeightedMidPoint(CameraTargets); var cameraTargetPositionX = FollowHorizontal ? Vector3H(targetsMidPoint) : Vector3H(_transform.localPosition); var cameraTargetPositionY = FollowVertical ? Vector3V(targetsMidPoint) : Vector3V(_transform.localPosition); var finalPos = new Vector2(cameraTargetPositionX, cameraTargetPositionY); finalPos += new Vector2(OverallOffset.x, OverallOffset.y); MoveCameraInstantlyToPosition(finalPos); } else { _cameraTargetPosition = _transform.localPosition; _cameraTargetHorizontalPositionSmoothed = Vector3H(_cameraTargetPosition); _previousCameraTargetHorizontalPositionSmoothed = _cameraTargetHorizontalPositionSmoothed; _cameraTargetVerticalPositionSmoothed = Vector3V(_cameraTargetPosition); _previousCameraTargetVerticalPositionSmoothed = _cameraTargetVerticalPositionSmoothed; } }
void Awake() { cam = GetComponent <tk2dCamera>(); }
void DrawConfigGUI(tk2dCamera _target) { bool cameraOverrideChanged = false; GUILayout.Space(8); // Game view stuff float gameViewPixelWidth = 0, gameViewPixelHeight = 0; float gameViewAspect = 0; bool gameViewFound = tk2dCamera.Editor__GetGameViewSize( out gameViewPixelWidth, out gameViewPixelHeight, out gameViewAspect); bool gameViewReflectionError = tk2dCamera.Editor__gameViewReflectionError; bool gameViewResolutionSet = (gameViewFound && gameViewPixelWidth != 0 && gameViewPixelHeight != 0); if (!gameViewFound && ++refreshCount < 3) { HandleUtility.Repaint(); } // Native resolution Vector2 nativeRes = new Vector2(_target.nativeResolutionWidth, _target.nativeResolutionHeight); EditorGUI.BeginChangeCheck(); nativeRes = ResolutionControl("Native Resolution", nativeRes); if (EditorGUI.EndChangeCheck()) { _target.nativeResolutionWidth = (int)nativeRes.x; _target.nativeResolutionHeight = (int)nativeRes.y; } // Preview resolution if (gameViewFound && gameViewResolutionSet) { if (_target.forceResolutionInEditor == false || _target.forceResolution.x != gameViewPixelWidth || _target.forceResolution.y != gameViewPixelHeight) { _target.forceResolutionInEditor = true; _target.forceResolution.Set( gameViewPixelWidth, gameViewPixelHeight ); GUI.changed = true; } ResolutionControl("Preview Resolution", _target.forceResolution); } else { EditorGUILayout.LabelField("Preview Resolution"); EditorGUI.indentLevel++; GUIContent toggleLabel = new GUIContent("Force Resolution", "When enabled, forces the resolution in the editor regardless of the size of the game window."); if (gameViewReflectionError) { EditorGUILayout.HelpBox("Game window resolution can't be detected.\n\n" + "tk2dCamera can't detect the game view resolution, possibly because of a Unity upgrade. You might need a 2D Toolkit update, or alternatively pick a resolution below.\n", MessageType.Error); } else if (gameViewFound) { EditorGUILayout.HelpBox("Game window has an aspect ratio selected.\n\n" + "tk2dCamera doesn't know your preview resolution, select from the list below, or pick a resolution in the game view instead.\n", MessageType.Info); } else { EditorGUILayout.HelpBox("Unable to detect game window resolution.\n\n" + "Ensure that the game window resolution is set, instead of selecting Free Aspect.\n", MessageType.Error); } tk2dGuiUtility.BeginChangeCheck(); _target.forceResolutionInEditor = EditorGUILayout.Toggle(toggleLabel, _target.forceResolutionInEditor); if (tk2dGuiUtility.EndChangeCheck()) cameraOverrideChanged = true; if (_target.forceResolutionInEditor) { tk2dGuiUtility.BeginChangeCheck(); List<Preset> presetList = null; if (gameViewFound) { presetList = new List<Preset>(from t in presets where t.MatchAspect( gameViewAspect ) select t); } else { presetList = new List<Preset>( presets ); } int currentSelectedResolution = presetList.FindIndex( x => x.width == _target.forceResolution.x && x.height == _target.forceResolution.y ); if (currentSelectedResolution == -1) { currentSelectedResolution = presetList.Count - 1; } string[] presetNames = (from t in presetList select t.name).ToArray(); int selectedResolution = EditorGUILayout.Popup("Preset", currentSelectedResolution, presetNames); if (selectedResolution != presetList.Count && selectedResolution != currentSelectedResolution) { var preset = presetList[selectedResolution]; _target.forceResolution.x = preset.width; _target.forceResolution.y = preset.height; GUI.changed = true; } if (gameViewFound // we only want to display warning when a resolution hasn't been selected from the list of known res / aspects && currentSelectedResolution == presetList.Count - 1) { float targetAspect = _target.forceResolution.y / Mathf.Max(_target.forceResolution.x, 0.01f); if (Mathf.Abs(targetAspect - gameViewAspect) > 0.01f) { EditorGUILayout.HelpBox("The preview resolution looks incorrect.\n\n" + "It looks like you've selected a preview resolution that doesn't match the game view aspect ratio.\n", MessageType.Error); } } _target.forceResolution.x = EditorGUILayout.IntField("Width", (int)_target.forceResolution.x); _target.forceResolution.y = EditorGUILayout.IntField("Height", (int)_target.forceResolution.y); // clamp to a sensible value _target.forceResolution.x = Mathf.Max(_target.forceResolution.x, 50); _target.forceResolution.y = Mathf.Max(_target.forceResolution.y, 50); if (tk2dGuiUtility.EndChangeCheck()) cameraOverrideChanged = true; } else { EditorGUILayout.FloatField("Width", _target.TargetResolution.x); EditorGUILayout.FloatField("Height", _target.TargetResolution.y); } EditorGUI.indentLevel--; } // Camera GUI is not available when inheriting configuration GUILayout.Space(16); DrawCameraGUI(_target, false); if (cameraOverrideChanged) { // Propagate values to all tk2dCameras in scene tk2dCamera[] otherCameras = Resources.FindObjectsOfTypeAll(typeof(tk2dCamera)) as tk2dCamera[]; foreach (tk2dCamera thisCamera in otherCameras) { thisCamera.forceResolutionInEditor = _target.forceResolutionInEditor; thisCamera.forceResolution = _target.forceResolution; thisCamera.UpdateCameraMatrix(); } // Update all anchors after that tk2dCameraAnchor[] anchors = Resources.FindObjectsOfTypeAll(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var anchor in anchors) anchor.ForceUpdateTransform(); } }
void DrawCameraGUI(tk2dCamera target, bool complete) { bool allowProjectionParameters = target.SettingsRoot == target; bool oldGuiEnabled = GUI.enabled; SerializedObject so = this.serializedObject; SerializedProperty m_ClearFlags = so.FindProperty("cameraSettings.clearFlags"); SerializedProperty m_BackGroundColor = so.FindProperty("cameraSettings.backgroundColor"); SerializedProperty m_CullingMask = so.FindProperty("cameraSettings.cullingMask"); SerializedProperty m_TargetTexture = so.FindProperty("cameraSettings.targetTexture"); if (complete) { EditorGUILayout.PropertyField(m_ClearFlags); EditorGUILayout.PropertyField(m_BackGroundColor); EditorGUILayout.PropertyField(m_CullingMask); EditorGUILayout.Space(); } tk2dCameraSettings cameraSettings = target.CameraSettings; tk2dCameraSettings inheritedSettings = target.SettingsRoot.CameraSettings; GUI.enabled &= allowProjectionParameters; inheritedSettings.projection = (tk2dCameraSettings.ProjectionType)EditorGUILayout.EnumPopup("Projection", inheritedSettings.projection); EditorGUI.indentLevel++; if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic) { inheritedSettings.orthographicType = (tk2dCameraSettings.OrthographicType)EditorGUILayout.EnumPopup("Type", inheritedSettings.orthographicType); switch (inheritedSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: inheritedSettings.orthographicSize = Mathf.Max(0.001f, EditorGUILayout.FloatField("Orthographic Size", inheritedSettings.orthographicSize)); break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: inheritedSettings.orthographicPixelsPerMeter = Mathf.Max(0.001f, EditorGUILayout.FloatField("Pixels per Meter", inheritedSettings.orthographicPixelsPerMeter)); break; } inheritedSettings.orthographicOrigin = (tk2dCameraSettings.OrthographicOrigin)EditorGUILayout.EnumPopup("Origin", inheritedSettings.orthographicOrigin); } else if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { inheritedSettings.fieldOfView = EditorGUILayout.Slider("Field of View", inheritedSettings.fieldOfView, 1, 179); inheritedSettings.transparencySortMode = (TransparencySortMode)EditorGUILayout.EnumPopup("Sort mode", inheritedSettings.transparencySortMode); } EditorGUI.indentLevel--; GUI.enabled = oldGuiEnabled; if (complete) { EditorGUILayout.Space(); GUILayout.Label("Clipping Planes"); GUILayout.BeginHorizontal(); GUILayout.Space(14); GUILayout.Label("Near"); cameraSettings.nearClipPlane = Mathf.Min(EditorGUILayout.FloatField(cameraSettings.nearClipPlane), cameraSettings.farClipPlane - 0.01f); GUILayout.Label("Far"); cameraSettings.farClipPlane = Mathf.Max(EditorGUILayout.FloatField(cameraSettings.farClipPlane), cameraSettings.nearClipPlane + 0.01f); GUILayout.EndHorizontal(); cameraSettings.rect = EditorGUILayout.RectField("Normalized View Port Rect", cameraSettings.rect); EditorGUILayout.Space(); cameraSettings.depth = EditorGUILayout.FloatField("Depth", cameraSettings.depth); cameraSettings.renderingPath = (RenderingPath)EditorGUILayout.EnumPopup("Rendering Path", cameraSettings.renderingPath); if (m_TargetTexture != null) { EditorGUILayout.PropertyField(m_TargetTexture); } cameraSettings.hdr = EditorGUILayout.Toggle("HDR", cameraSettings.hdr); } so.ApplyModifiedProperties(); }
public void OnSceneGUI(tk2dCamera target) { this.target = target; if (previewCamera == null) { GameObject go = EditorUtility.CreateGameObjectWithHideFlags("@tk2dCamera_ScenePreview", UnityEngine.HideFlags.HideAndDontSave, new System.Type[] { typeof(Camera) } ); previewCamera = go.camera; previewCamera.enabled = false; } Vector2 resolution = target.TargetResolution; float maxHeight = Screen.height / 5; float fWidth, fHeight; fHeight = maxHeight; fWidth = resolution.x / resolution.y * maxHeight; int windowDecorationWidth = 11; int windowDecorationHeight = 24; int width = (int)fWidth + windowDecorationWidth; int height = (int)fHeight + windowDecorationHeight; string windowCaption = "tk2dCamera"; if (width > 200) windowCaption += string.Format(" ({0:0} x {1:0})", resolution.x, resolution.y); int viewportOffsetLeft = 10; int viewportOffsetBottom = -8; previewWindowRect = new Rect(viewportOffsetLeft, Camera.current.pixelHeight - height - viewportOffsetBottom, width, height); Handles.BeginGUI(); GUI.Window("tk2dCamera Preview".GetHashCode(), previewWindowRect, PreviewWindowFunc, windowCaption); Handles.EndGUI(); }
void Awake() { _instance = this; _transform = transform; if (GameCamera == null) { GameCamera = GetComponent <Camera>(); } if (GameCamera == null) { Debug.LogError("Unity Camera not set and not found on the GameObject: " + gameObject.name); } #if PC2D_TK2D_SUPPORT Tk2dCam = GetComponent <tk2dCamera>(); #endif switch (Axis) { case MovementAxis.XY: Vector3H = vector => vector.x; Vector3V = vector => vector.y; Vector3D = vector => vector.z; VectorHV = (h, v) => new Vector3(h, v, 0); VectorHVD = (h, v, d) => new Vector3(h, v, d); break; case MovementAxis.XZ: Vector3H = vector => vector.x; Vector3V = vector => vector.z; Vector3D = vector => vector.y; VectorHV = (h, v) => new Vector3(h, 0, v); VectorHVD = (h, v, d) => new Vector3(h, d, v); break; case MovementAxis.YZ: Vector3H = vector => vector.z; Vector3V = vector => vector.y; Vector3D = vector => vector.x; VectorHV = (h, v) => new Vector3(0, v, h); VectorHVD = (h, v, d) => new Vector3(d, v, h); break; } // Remove empty targets for (int i = 0; i < CameraTargets.Count; i++) { if (CameraTargets [i].TargetTransform == null) { CameraTargets.RemoveAt(i); } } ScreenSizeInWorldCoordinates = Utils.GetScreenSizeInWorldCoords(GameCamera, Mathf.Abs(Vector3D(_transform.localPosition))); _cameraWindowRectInWorldCoords = GetRectAroundTransf(CameraWindowRect, ScreenSizeInWorldCoordinates, _transform); _cameraMoveInColliderBoundaries = new MoveInColliderBoundaries(this); _cameraMoveInColliderBoundaries.CameraTransform = _transform; _cameraMoveInColliderBoundaries.CameraSize = ScreenSizeInWorldCoordinates; _cameraMoveInColliderBoundaries.CameraCollisionMask = BoundariesLayerMask; _originalCameraDepthSign = Mathf.Sign(Vector3D(_transform.localPosition)); _transform.parent = new GameObject(gameObject.name + " Container").transform; // Center on target if (CenterTargetOnStart && CameraTargets.Count > 0) { var targetPos = GetTargetsWeightedMidPoint(CameraTargets); var cameraTargetPositionX = FollowHorizontal ? Vector3H(targetPos) : Vector3H(_transform.localPosition); var cameraTargetPositionY = FollowVertical ? Vector3V(targetPos) : Vector3V(_transform.localPosition); targetPos = VectorHV(cameraTargetPositionX, cameraTargetPositionY); targetPos += VectorHV(OverallOffset.x, OverallOffset.y); MoveCameraInstantlyToPosition(targetPos); } else { _cameraTargetPosition = _transform.localPosition; _cameraTargetHorizontalPositionSmoothed = Vector3H(_cameraTargetPosition); _previousCameraTargetHorizontalPositionSmoothed = _cameraTargetHorizontalPositionSmoothed; _cameraTargetVerticalPositionSmoothed = Vector3V(_cameraTargetPosition); _previousCameraTargetVerticalPositionSmoothed = _cameraTargetVerticalPositionSmoothed; } }
// Use this for initialization void Awake() { mainCamera = GetComponent<Camera>(); if (mainCamera != null) { UpdateCameraMatrix(); } if (!viewportClippingEnabled) // the main camera can't display rect inst = this; }
void DrawConfigGUI(tk2dCamera _target) { bool cameraOverrideChanged = false; GUILayout.Space(8); // Game view stuff float gameViewPixelWidth = 0, gameViewPixelHeight = 0; float gameViewAspect = 0; bool gameViewFound = tk2dCamera.Editor__GetGameViewSize(out gameViewPixelWidth, out gameViewPixelHeight, out gameViewAspect); bool gameViewReflectionError = tk2dCamera.Editor__gameViewReflectionError; bool gameViewResolutionSet = (gameViewFound && gameViewPixelWidth != 0 && gameViewPixelHeight != 0); if (!gameViewFound && ++refreshCount < 3) { HandleUtility.Repaint(); } // Native resolution Vector2 nativeRes = new Vector2(_target.nativeResolutionWidth, _target.nativeResolutionHeight); EditorGUI.BeginChangeCheck(); nativeRes = ResolutionControl("Native Resolution", nativeRes); if (EditorGUI.EndChangeCheck()) { _target.nativeResolutionWidth = (int)nativeRes.x; _target.nativeResolutionHeight = (int)nativeRes.y; } // Preview resolution if (gameViewFound && gameViewResolutionSet) { if (_target.forceResolutionInEditor == false || _target.forceResolution.x != gameViewPixelWidth || _target.forceResolution.y != gameViewPixelHeight) { _target.forceResolutionInEditor = true; _target.forceResolution.Set(gameViewPixelWidth, gameViewPixelHeight); GUI.changed = true; } ResolutionControl("Preview Resolution", _target.forceResolution); } else { EditorGUILayout.LabelField("Preview Resolution"); EditorGUI.indentLevel++; GUIContent toggleLabel = new GUIContent("Force Resolution", "When enabled, forces the resolution in the editor regardless of the size of the game window."); if (gameViewReflectionError) { EditorGUILayout.HelpBox("Game window resolution can't be detected.\n\n" + "tk2dCamera can't detect the game view resolution, possibly because of a Unity upgrade. You might need a 2D Toolkit update, or alternatively pick a resolution below.\n", MessageType.Error); } else if (gameViewFound) { EditorGUILayout.HelpBox("Game window has an aspect ratio selected.\n\n" + "tk2dCamera doesn't know your preview resolution, select from the list below, or pick a resolution in the game view instead.\n", MessageType.Info); } else { EditorGUILayout.HelpBox("Unable to detect game window resolution.\n\n" + "Ensure that the game window resolution is set, instead of selecting Free Aspect.\n", MessageType.Error); } tk2dGuiUtility.BeginChangeCheck(); _target.forceResolutionInEditor = EditorGUILayout.Toggle(toggleLabel, _target.forceResolutionInEditor); if (tk2dGuiUtility.EndChangeCheck()) { cameraOverrideChanged = true; } if (_target.forceResolutionInEditor) { tk2dGuiUtility.BeginChangeCheck(); List <Preset> presetList = null; if (gameViewFound) { presetList = new List <Preset>(from t in presets where t.MatchAspect(gameViewAspect) select t); } else { presetList = new List <Preset>(presets); } int currentSelectedResolution = presetList.FindIndex(x => x.width == _target.forceResolution.x && x.height == _target.forceResolution.y); if (currentSelectedResolution == -1) { currentSelectedResolution = presetList.Count - 1; } string[] presetNames = (from t in presetList select t.name).ToArray(); int selectedResolution = EditorGUILayout.Popup("Preset", currentSelectedResolution, presetNames); if (selectedResolution != presetList.Count && selectedResolution != currentSelectedResolution) { var preset = presetList[selectedResolution]; _target.forceResolution.x = preset.width; _target.forceResolution.y = preset.height; GUI.changed = true; } if (gameViewFound && // we only want to display warning when a resolution hasn't been selected from the list of known res / aspects currentSelectedResolution == presetList.Count - 1) { float targetAspect = _target.forceResolution.y / Mathf.Max(_target.forceResolution.x, 0.01f); if (Mathf.Abs(targetAspect - gameViewAspect) > 0.01f) { EditorGUILayout.HelpBox("The preview resolution looks incorrect.\n\n" + "It looks like you've selected a preview resolution that doesn't match the game view aspect ratio.\n", MessageType.Error); } } _target.forceResolution.x = EditorGUILayout.IntField("Width", (int)_target.forceResolution.x); _target.forceResolution.y = EditorGUILayout.IntField("Height", (int)_target.forceResolution.y); // clamp to a sensible value _target.forceResolution.x = Mathf.Max(_target.forceResolution.x, 50); _target.forceResolution.y = Mathf.Max(_target.forceResolution.y, 50); if (tk2dGuiUtility.EndChangeCheck()) { cameraOverrideChanged = true; } } else { EditorGUILayout.FloatField("Width", _target.TargetResolution.x); EditorGUILayout.FloatField("Height", _target.TargetResolution.y); } EditorGUI.indentLevel--; } // Camera GUI is not available when inheriting configuration GUILayout.Space(16); DrawCameraGUI(_target, false); if (cameraOverrideChanged) { // Propagate values to all tk2dCameras in scene tk2dCamera[] otherCameras = Resources.FindObjectsOfTypeAll(typeof(tk2dCamera)) as tk2dCamera[]; foreach (tk2dCamera thisCamera in otherCameras) { thisCamera.forceResolutionInEditor = _target.forceResolutionInEditor; thisCamera.forceResolution = _target.forceResolution; thisCamera.UpdateCameraMatrix(); } // Update all anchors after that tk2dCameraAnchor[] anchors = Resources.FindObjectsOfTypeAll(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var anchor in anchors) { anchor.ForceUpdateTransform(); } } }
void Start() { objCamera = (tk2dCamera) GameObject.FindWithTag("MainCamera").GetComponent<tk2dCamera>(); objPlayer = (GameObject) GameObject.FindWithTag("Player"); objScriptVariable = (VariableScript)objPlayer.GetComponent(typeof(VariableScript)); objSprite = GetComponent<tk2dSprite>(); objBarrel = GameObjectUtilts.FindChild(gameObject.name, "Barrel"); missileOrigin = objBarrel.transform.Find("BulletOrigin"); health = maxHealth; }
void DrawCameraGUI(tk2dCamera target, bool complete) { bool allowProjectionParameters = target.SettingsRoot == target; bool oldGuiEnabled = GUI.enabled; SerializedObject so = this.serializedObject; SerializedObject cam = new SerializedObject(target.GetComponent <Camera>()); SerializedProperty m_ClearFlags = cam.FindProperty("m_ClearFlags"); SerializedProperty m_BackGroundColor = cam.FindProperty("m_BackGroundColor"); SerializedProperty m_CullingMask = cam.FindProperty("m_CullingMask"); SerializedProperty m_TargetTexture = cam.FindProperty("m_TargetTexture"); SerializedProperty m_Near = cam.FindProperty("near clip plane"); SerializedProperty m_Far = cam.FindProperty("far clip plane"); SerializedProperty m_Depth = cam.FindProperty("m_Depth"); SerializedProperty m_RenderingPath = cam.FindProperty("m_RenderingPath"); SerializedProperty m_HDR = cam.FindProperty("m_HDR"); if (complete) { EditorGUILayout.PropertyField(m_ClearFlags); EditorGUILayout.PropertyField(m_BackGroundColor); EditorGUILayout.PropertyField(m_CullingMask); EditorGUILayout.Space(); } tk2dCameraSettings cameraSettings = target.CameraSettings; tk2dCameraSettings inheritedSettings = target.SettingsRoot.CameraSettings; TransparencySortMode transparencySortMode = inheritedSettings.transparencySortMode; GUI.enabled &= allowProjectionParameters; inheritedSettings.projection = (tk2dCameraSettings.ProjectionType)EditorGUILayout.EnumPopup("Projection", inheritedSettings.projection); EditorGUI.indentLevel++; if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic) { inheritedSettings.orthographicType = (tk2dCameraSettings.OrthographicType)EditorGUILayout.EnumPopup("Type", inheritedSettings.orthographicType); switch (inheritedSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: inheritedSettings.orthographicSize = Mathf.Max(0.001f, EditorGUILayout.FloatField("Orthographic Size", inheritedSettings.orthographicSize)); break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: inheritedSettings.orthographicPixelsPerMeter = Mathf.Max(0.001f, EditorGUILayout.FloatField("Pixels per Meter", inheritedSettings.orthographicPixelsPerMeter)); break; } inheritedSettings.orthographicOrigin = (tk2dCameraSettings.OrthographicOrigin)EditorGUILayout.EnumPopup("Origin", inheritedSettings.orthographicOrigin); } else if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { inheritedSettings.fieldOfView = EditorGUILayout.Slider("Field of View", inheritedSettings.fieldOfView, 1, 179); transparencySortMode = (TransparencySortMode)EditorGUILayout.EnumPopup("Sort mode", transparencySortMode); } EditorGUI.indentLevel--; GUI.enabled = oldGuiEnabled; if (complete) { EditorGUILayout.Space(); GUILayout.Label("Clipping Planes"); GUILayout.BeginHorizontal(); GUILayout.Space(14); GUILayout.Label("Near"); if (m_Near != null) { EditorGUILayout.PropertyField(m_Near, GUIContent.none, GUILayout.Width(60)); } GUILayout.Label("Far"); if (m_Far != null) { EditorGUILayout.PropertyField(m_Far, GUIContent.none, GUILayout.Width(60)); } GUILayout.EndHorizontal(); cameraSettings.rect = EditorGUILayout.RectField("Normalized View Port Rect", cameraSettings.rect); EditorGUILayout.Space(); if (m_Depth != null) { EditorGUILayout.PropertyField(m_Depth); } if (m_RenderingPath != null) { EditorGUILayout.PropertyField(m_RenderingPath); } if (m_TargetTexture != null) { EditorGUILayout.PropertyField(m_TargetTexture); } if (m_HDR != null) { EditorGUILayout.PropertyField(m_HDR); } } cam.ApplyModifiedProperties(); so.ApplyModifiedProperties(); if (transparencySortMode != inheritedSettings.transparencySortMode) { inheritedSettings.transparencySortMode = transparencySortMode; target.GetComponent <Camera>().transparencySortMode = transparencySortMode; // Change immediately in the editor tk2dUtil.SetDirty(target); tk2dUtil.SetDirty(target.GetComponent <Camera>()); } }
void UpdateTransform() { // Break out if anchor camera is not bound if (AnchorCamera == null) { return; } float pixelScale = 1; // size of one pixel Vector3 position = myTransform.localPosition; // we're ignoring perspective tk2dCameras for now tk2dCamera = (AnchorTk2dCamera != null && AnchorTk2dCamera.CameraSettings.projection != tk2dCameraSettings.ProjectionType.Perspective) ? AnchorTk2dCamera : null; Rect rect = new Rect(); if (tk2dCamera != null) { rect = anchorToNativeBounds ? tk2dCamera.NativeScreenExtents : tk2dCamera.ScreenExtents; pixelScale = tk2dCamera.GetSizeAtDistance( 1 ); } else { rect.Set(0, 0, AnchorCamera.pixelWidth, AnchorCamera.pixelHeight); } float y_bot = rect.yMin; float y_top = rect.yMax; float y_ctr = (y_bot + y_top) * 0.5f; float x_lhs = rect.xMin; float x_rhs = rect.xMax; float x_ctr = (x_lhs + x_rhs) * 0.5f; Vector3 anchoredPosition = Vector3.zero; switch (AnchorPoint) { case tk2dBaseSprite.Anchor.UpperLeft: anchoredPosition = new Vector3(x_lhs, y_top, position.z); break; case tk2dBaseSprite.Anchor.UpperCenter: anchoredPosition = new Vector3(x_ctr, y_top, position.z); break; case tk2dBaseSprite.Anchor.UpperRight: anchoredPosition = new Vector3(x_rhs, y_top, position.z); break; case tk2dBaseSprite.Anchor.MiddleLeft: anchoredPosition = new Vector3(x_lhs, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.MiddleCenter: anchoredPosition = new Vector3(x_ctr, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.MiddleRight: anchoredPosition = new Vector3(x_rhs, y_ctr, position.z); break; case tk2dBaseSprite.Anchor.LowerLeft: anchoredPosition = new Vector3(x_lhs, y_bot, position.z); break; case tk2dBaseSprite.Anchor.LowerCenter: anchoredPosition = new Vector3(x_ctr, y_bot, position.z); break; case tk2dBaseSprite.Anchor.LowerRight: anchoredPosition = new Vector3(x_rhs, y_bot, position.z); break; } Vector3 screenAnchoredPosition = anchoredPosition + new Vector3(pixelScale * offset.x, pixelScale * offset.y, 0); if (tk2dCamera == null) { // not a tk2dCamera, we need to transform Vector3 worldAnchoredPosition = AnchorCamera.ScreenToWorldPoint( screenAnchoredPosition ); if (myTransform.position != worldAnchoredPosition) { myTransform.position = worldAnchoredPosition; } } else { Vector3 oldPosition = myTransform.localPosition; if (oldPosition != screenAnchoredPosition) { myTransform.localPosition = screenAnchoredPosition; } } }
void DrawOverrideGUI(tk2dCamera _camera) { var frameBorderStyle = EditorStyles.textField; tk2dGuiUtility.LookLikeControls(64); tk2dCamera _target = _camera.SettingsRoot; if (_target.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { tk2dGuiUtility.InfoBox("Overrides not supported with perspective camera.", tk2dGuiUtility.WarningLevel.Info); } else { GUI.enabled = _target == _camera; tk2dCameraResolutionOverride usedOverride = _target.CurrentResolutionOverride; if (_target.resolutionOverride.Length == 0) { EditorGUILayout.HelpBox("There are no overrides on this tk2dCamera.\n\nThe camera will always scale itself to be pixel perfect at any resolution. " + "Add an override if you wish to change this behaviour.", MessageType.Warning); } else { EditorGUILayout.HelpBox("Matching is performed from top to bottom. The first override matching the current resolution will be used.", MessageType.Info); } System.Action <int> deferredAction = null; for (int i = 0; i < _target.resolutionOverride.Length; ++i) { tk2dCameraResolutionOverride ovr = _target.resolutionOverride[i]; EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(8); GUILayout.BeginHorizontal(); ovr.name = EditorGUILayout.TextField("Name", ovr.name); GUI.enabled = (i != _target.resolutionOverride.Length - 1); if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_down"))) { int idx = i; deferredAction = delegate(int q) { _target.resolutionOverride[idx] = _target.resolutionOverride[idx + 1]; _target.resolutionOverride[idx + 1] = ovr; }; } GUI.enabled = (i != 0); if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_up"))) { int idx = i; deferredAction = delegate(int q) { _target.resolutionOverride[idx] = _target.resolutionOverride[idx - 1]; _target.resolutionOverride[idx - 1] = ovr; }; } GUI.enabled = true; if (GUILayout.Button("", tk2dEditorSkin.GetStyle("TilemapDeleteItem"))) { int idx = i; deferredAction = delegate(int q) { List <tk2dCameraResolutionOverride> list = new List <tk2dCameraResolutionOverride>(_target.resolutionOverride); list.RemoveAt(idx); _target.resolutionOverride = list.ToArray(); }; } GUILayout.EndHorizontal(); ovr.matchBy = (tk2dCameraResolutionOverride.MatchByType)EditorGUILayout.EnumPopup("Match By", ovr.matchBy); int tmpIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; switch (ovr.matchBy) { case tk2dCameraResolutionOverride.MatchByType.Wildcard: break; case tk2dCameraResolutionOverride.MatchByType.Resolution: Vector2 res = new Vector2(ovr.width, ovr.height); res = ResolutionControl(" ", res); ovr.width = (int)res.x; ovr.height = (int)res.y; break; case tk2dCameraResolutionOverride.MatchByType.AspectRatio: GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); ovr.aspectRatioNumerator = EditorGUILayout.FloatField(ovr.aspectRatioNumerator, GUILayout.Width(40)); GUILayout.Label(":", GUILayout.ExpandWidth(false)); ovr.aspectRatioDenominator = EditorGUILayout.FloatField(ovr.aspectRatioDenominator, GUILayout.Width(40)); GUILayout.EndHorizontal(); break; } EditorGUI.indentLevel = tmpIndent; ovr.autoScaleMode = (tk2dCameraResolutionOverride.AutoScaleMode)EditorGUILayout.EnumPopup("Auto Scale", ovr.autoScaleMode); if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.None) { EditorGUI.indentLevel++; ovr.scale = EditorGUILayout.FloatField("Scale", ovr.scale); EditorGUI.indentLevel--; } if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit) { string msg = "The native resolution image will be stretched to fit the target display. " + "Image quality will suffer if non-uniform scaling occurs."; tk2dGuiUtility.InfoBox(msg, tk2dGuiUtility.WarningLevel.Info); } else { ovr.fitMode = (tk2dCameraResolutionOverride.FitMode)EditorGUILayout.EnumPopup("Fit Mode", ovr.fitMode); if (ovr.fitMode == tk2dCameraResolutionOverride.FitMode.Constant) { EditorGUI.indentLevel++; ovr.offsetPixels.x = EditorGUILayout.FloatField("X", ovr.offsetPixels.x); ovr.offsetPixels.y = EditorGUILayout.FloatField("Y", ovr.offsetPixels.y); EditorGUI.indentLevel--; } } GUILayout.Space(4); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (ovr == usedOverride) { GUI.color = Color.green; GUIContent content = new GUIContent("ACTIVE", "The active override is the one that matches the current resolution, and is being used in the tk2dCamera game window."); GUILayout.Label(content, EditorStyles.miniBoldLabel, GUILayout.ExpandWidth(false)); GUI.color = Color.white; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } if (deferredAction != null) { deferredAction(0); GUI.changed = true; Repaint(); } EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(32); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add override", GUILayout.ExpandWidth(false))) { tk2dCameraResolutionOverride ovr = new tk2dCameraResolutionOverride(); ovr.name = "New override"; ovr.matchBy = tk2dCameraResolutionOverride.MatchByType.Wildcard; ovr.autoScaleMode = tk2dCameraResolutionOverride.AutoScaleMode.FitVisible; ovr.fitMode = tk2dCameraResolutionOverride.FitMode.Center; System.Array.Resize(ref _target.resolutionOverride, _target.resolutionOverride.Length + 1); _target.resolutionOverride[_target.resolutionOverride.Length - 1] = ovr; GUI.changed = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(32); EditorGUILayout.EndVertical(); GUI.enabled = true; } }
/// <summary> /// Inits the camera. /// </summary> public static void InitCamera() { tkCamera = Camera.main.GetComponent<tk2dCamera>(); }
public override void OnInspectorGUI() { //DrawDefaultInspector(); tk2dCamera _target = (tk2dCamera)target; // sanity if (_target.resolutionOverride == null) { _target.resolutionOverride = new tk2dCameraResolutionOverride[0]; GUI.changed = true; } string[] toolbarButtons = new string[] { "General", "Camera", "Overrides", "Advanced" }; toolbarSelection = GUILayout.Toolbar(toolbarSelection, toolbarButtons); GUILayout.Space(16); if (toolbarSelection == 0) { GUILayout.BeginHorizontal(); tk2dCamera newInherit = EditorGUILayout.ObjectField("Inherit config", _target.InheritConfig, typeof(tk2dCamera), true) as tk2dCamera; if (newInherit != _target.InheritConfig) { if (newInherit != _target) { _target.InheritConfig = newInherit; } else { EditorUtility.DisplayDialog("Error", "Can't inherit from self", "Ok"); } } if (_target.InheritConfig != null && GUILayout.Button("Clear", GUILayout.ExpandWidth(false))) { _target.InheritConfig = null; GUI.changed = true; } GUILayout.EndHorizontal(); GUI.enabled = _target.SettingsRoot == _target; DrawConfigGUI(_target.SettingsRoot); GUI.enabled = true; GUILayout.Space(16); _target.ZoomFactor = EditorGUILayout.FloatField("Zoom factor", _target.ZoomFactor); } if (toolbarSelection == 1) { DrawCameraGUI(_target, true); } if (toolbarSelection == 2) { // Overrides DrawOverrideGUI(_target); } if (toolbarSelection == 3) { bool isPerspective = _target.SettingsRoot.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective; tk2dGuiUtility.InfoBox("Anchored viewport clipping is a legacy feature which will be removed in a future version of 2D Toolkit.\n", tk2dGuiUtility.WarningLevel.Warning); EditorGUILayout.LabelField("Anchored Viewport Clipping", EditorStyles.boldLabel); EditorGUI.indentLevel++; if (_target.InheritConfig == null || isPerspective) { _target.viewportClippingEnabled = false; GUI.enabled = false; EditorGUILayout.Toggle("Enable", false); GUI.enabled = true; if (isPerspective) { tk2dGuiUtility.InfoBox("Anchored viewport clipping not allowed on perspective cameras.\n", tk2dGuiUtility.WarningLevel.Error); } else { tk2dGuiUtility.InfoBox("Anchored viewport clipping not allowed on this camera.\nAttach a link to a camera which displays the entire screen to enable viewport clipping.", tk2dGuiUtility.WarningLevel.Error); } } else { _target.viewportClippingEnabled = EditorGUILayout.Toggle("Enable", _target.viewportClippingEnabled); if (_target.viewportClippingEnabled) { EditorGUILayout.LabelField("Region"); EditorGUI.indentLevel++; _target.viewportRegion.x = EditorGUILayout.IntField("X", (int)_target.viewportRegion.x); _target.viewportRegion.y = EditorGUILayout.IntField("Y", (int)_target.viewportRegion.y); _target.viewportRegion.z = EditorGUILayout.IntField("Width", (int)_target.viewportRegion.z); _target.viewportRegion.w = EditorGUILayout.IntField("Height", (int)_target.viewportRegion.w); EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; } if (GUI.changed) { _target.UpdateCameraMatrix(); tk2dUtil.SetDirty(target); tk2dCameraAnchor[] allAlignmentObjects = GameObject.FindObjectsOfType(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var v in allAlignmentObjects) { tk2dUtil.SetDirty(v); } } GUILayout.Space(16.0f); }
void Awake() { _instance = this; _transform = transform; if (GameCamera == null) GameCamera = GetComponent<Camera>(); if (GameCamera == null) Debug.LogError("Unity Camera not set and not found on the GameObject: " + gameObject.name); #if PC2D_TK2D_SUPPORT Tk2dCam = GetComponent<tk2dCamera>(); #endif switch (Axis) { case MovementAxis.XY: Vector3H = vector => vector.x; Vector3V = vector => vector.y; Vector3D = vector => vector.z; VectorHV = (h, v) => new Vector3(h, v, 0); VectorHVD = (h, v, d) => new Vector3(h, v, d); break; case MovementAxis.XZ: Vector3H = vector => vector.x; Vector3V = vector => vector.z; Vector3D = vector => vector.y; VectorHV = (h, v) => new Vector3(h, 0, v); VectorHVD = (h, v, d) => new Vector3(h, d, v); break; case MovementAxis.YZ: Vector3H = vector => vector.z; Vector3V = vector => vector.y; Vector3D = vector => vector.x; VectorHV = (h, v) => new Vector3(0, v, h); VectorHVD = (h, v, d) => new Vector3(d, v, h); break; } // Remove empty targets for (int i = 0; i < CameraTargets.Count; i++) { if (CameraTargets[i].TargetTransform == null) { CameraTargets.RemoveAt(i); } } ScreenSizeInWorldCoordinates = Utils.GetScreenSizeInWorldCoords(GameCamera, Mathf.Abs(Vector3D(_transform.localPosition))); _cameraDepthPos = Vector3D(_transform.localPosition); _originalCameraDepthSign = Mathf.Sign(_cameraDepthPos); _transform.parent = new GameObject(gameObject.name + " Container").transform; // Center on target if (CenterTargetOnStart && CameraTargets.Count > 0) { var targetPos = GetTargetsWeightedMidPoint(CameraTargets); var cameraTargetPositionX = FollowHorizontal ? Vector3H(targetPos) : Vector3H(_transform.localPosition); var cameraTargetPositionY = FollowVertical ? Vector3V(targetPos) : Vector3V(_transform.localPosition); targetPos = VectorHV(cameraTargetPositionX, cameraTargetPositionY); targetPos += VectorHV(OverallOffset.x, OverallOffset.y); MoveCameraInstantlyToPosition(targetPos); } else { _cameraTargetPosition = _transform.localPosition; _cameraTargetHorizontalPositionSmoothed = Vector3H(_cameraTargetPosition); _previousCameraTargetHorizontalPositionSmoothed = _cameraTargetHorizontalPositionSmoothed; _cameraTargetVerticalPositionSmoothed = Vector3V(_cameraTargetPosition); _previousCameraTargetVerticalPositionSmoothed = _cameraTargetVerticalPositionSmoothed; } }
protected override void Awake() { base.Awake(); mCam = Camera.main.GetComponentInChildren <tk2dCamera>(); }
Vector2 GetOffsetForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, Vector2 scale, float width, float height) { Vector2 offset = Vector2.zero; if (currentOverride == null) { return offset; } switch (currentOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.BottomLeft) { offset = new Vector2(Mathf.Round((settings.nativeResolutionWidth * scale.x - width ) / 2.0f), Mathf.Round((settings.nativeResolutionHeight * scale.y - height) / 2.0f)); } break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentOverride.offsetPixels; break; } return offset; }
// Use this for initialization void Start() { cam = GetComponent<tk2dCamera>(); }
Vector2 GetScaleForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float width, float height) { Vector2 scale = Vector2.one; float s = 1.0f; if (currentOverride == null) { return scale; } switch (currentOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfect: s = 1; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = height / settings.nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = width / settings.nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo: float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight; float currentAspect = width / height; if (currentAspect < nativeAspect) s = width / settings.nativeResolutionWidth; else s = height / settings.nativeResolutionHeight; if (currentOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo) { if (s > 1.0f) s = Mathf.Floor(s); // round number else s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentOverride.scale; scale.Set(s, s); break; } return scale; }
public override void OnInspectorGUI() { //DrawDefaultInspector(); tk2dCamera _target = (tk2dCamera)target; var frameBorderStyle = EditorStyles.textField; // sanity if (_target.resolutionOverride == null) { _target.resolutionOverride = new tk2dCameraResolutionOverride[0]; GUI.changed = true; } _target.enableResolutionOverrides = EditorGUILayout.Toggle("Resolution overrides", _target.enableResolutionOverrides); if (_target.enableResolutionOverrides) { EditorGUILayout.LabelField("Native resolution", EditorStyles.boldLabel); EditorGUI.indentLevel++; _target.nativeResolutionWidth = EditorGUILayout.IntField("Width", _target.nativeResolutionWidth); _target.nativeResolutionHeight = EditorGUILayout.IntField("Height", _target.nativeResolutionHeight); EditorGUI.indentLevel--; // Overrides EditorGUILayout.LabelField("Overrides", EditorStyles.boldLabel); EditorGUI.indentLevel++; int deleteId = -1; for (int i = 0; i < _target.resolutionOverride.Length; ++i) { var ovr = _target.resolutionOverride[i]; EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(8); ovr.name = EditorGUILayout.TextField("Name", ovr.name); ovr.width = EditorGUILayout.IntField("Width", ovr.width); ovr.height = EditorGUILayout.IntField("Height", ovr.height); ovr.autoScaleMode = (tk2dCameraResolutionOverride.AutoScaleMode)EditorGUILayout.EnumPopup("Auto Scale", ovr.autoScaleMode); if (ovr.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.None) { EditorGUI.indentLevel++; ovr.scale = EditorGUILayout.FloatField("Scale", ovr.scale); EditorGUI.indentLevel--; } ovr.fitMode = (tk2dCameraResolutionOverride.FitMode)EditorGUILayout.EnumPopup("Fit Mode", ovr.fitMode); if (ovr.fitMode == tk2dCameraResolutionOverride.FitMode.Constant) { EditorGUI.indentLevel++; ovr.offsetPixels.x = EditorGUILayout.FloatField("X", ovr.offsetPixels.x); ovr.offsetPixels.y = EditorGUILayout.FloatField("Y", ovr.offsetPixels.y); EditorGUI.indentLevel--; } GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); if (GUILayout.Button("Delete", EditorStyles.miniButton)) { deleteId = i; } GUILayout.EndHorizontal(); GUILayout.Space(4); EditorGUILayout.EndVertical(); } if (deleteId != -1) { List <tk2dCameraResolutionOverride> ovr = new List <tk2dCameraResolutionOverride>(_target.resolutionOverride); ovr.RemoveAt(deleteId); _target.resolutionOverride = ovr.ToArray(); GUI.changed = true; Repaint(); } EditorGUILayout.BeginVertical(frameBorderStyle); GUILayout.Space(32); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add override", GUILayout.ExpandWidth(false))) { tk2dCameraResolutionOverride ovr = new tk2dCameraResolutionOverride(); ovr.name = "Wildcard Override"; ovr.width = -1; ovr.height = -1; ovr.autoScaleMode = tk2dCameraResolutionOverride.AutoScaleMode.FitVisible; ovr.fitMode = tk2dCameraResolutionOverride.FitMode.Center; System.Array.Resize(ref _target.resolutionOverride, _target.resolutionOverride.Length + 1); _target.resolutionOverride[_target.resolutionOverride.Length - 1] = ovr; GUI.changed = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(32); EditorGUILayout.EndVertical(); EditorGUI.indentLevel--; } EditorGUILayout.Space(); EditorGUILayout.LabelField("Camera resolution", EditorStyles.boldLabel); GUIContent toggleLabel = new GUIContent("Force Editor Resolution", "When enabled, forces the resolution in the editor regardless of the size of the game window."); EditorGUI.indentLevel++; bool cameraOverrideChanged = false; tk2dGuiUtility.BeginChangeCheck(); _target.forceResolutionInEditor = EditorGUILayout.Toggle(toggleLabel, _target.forceResolutionInEditor); if (tk2dGuiUtility.EndChangeCheck()) { cameraOverrideChanged = true; } if (_target.forceResolutionInEditor) { tk2dGuiUtility.BeginChangeCheck(); int selectedResolution = EditorGUILayout.Popup("Preset", 0, presetListStr); if (selectedResolution != 0) { var preset = presets[selectedResolution - 1]; _target.forceResolution.x = preset.width; _target.forceResolution.y = preset.height; GUI.changed = true; } _target.forceResolution.x = EditorGUILayout.IntField("Width", (int)_target.forceResolution.x); _target.forceResolution.y = EditorGUILayout.IntField("Height", (int)_target.forceResolution.y); // clamp to a sensible value _target.forceResolution.x = Mathf.Max(_target.forceResolution.x, 50); _target.forceResolution.y = Mathf.Max(_target.forceResolution.y, 50); Rect r = GUILayoutUtility.GetRect(1, 1, GUILayout.ExpandWidth(true), GUILayout.MinHeight(43)); EditorGUI.HelpBox(new Rect(r.x + 4, r.y, r.width - 8, r.height), "Ensure that the the game view resolution is the same as the override chosen here, otherwise the game window will not display correctly.", MessageType.Warning); if (tk2dGuiUtility.EndChangeCheck()) { cameraOverrideChanged = true; } } else { EditorGUILayout.FloatField("Width", _target.TargetResolution.x); EditorGUILayout.FloatField("Height", _target.TargetResolution.y); } EditorGUI.indentLevel--; if (cameraOverrideChanged) { // Propagate values to all tk2dCameras in scene tk2dCamera[] otherCameras = Resources.FindObjectsOfTypeAll(typeof(tk2dCamera)) as tk2dCamera[]; foreach (tk2dCamera thisCamera in otherCameras) { thisCamera.forceResolutionInEditor = _target.forceResolutionInEditor; thisCamera.forceResolution = _target.forceResolution; thisCamera.UpdateCameraMatrix(); } // Update all anchors after that tk2dCameraAnchor[] anchors = Resources.FindObjectsOfTypeAll(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var anchor in anchors) { anchor.ForceUpdateTransform(); } } if (GUI.changed) { EditorUtility.SetDirty(target); tk2dCameraAnchor[] allAlignmentObjects = GameObject.FindObjectsOfType(typeof(tk2dCameraAnchor)) as tk2dCameraAnchor[]; foreach (var v in allAlignmentObjects) { EditorUtility.SetDirty(v); } } GUILayout.Space(16.0f); EditorGUILayout.LabelField("Tools", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("Create Anchor", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { tk2dCamera cam = (tk2dCamera)target; GameObject go = new GameObject("Anchor"); go.transform.parent = cam.transform; tk2dCameraAnchor cameraAnchor = go.AddComponent <tk2dCameraAnchor>(); cameraAnchor.tk2dCamera = cam; EditorGUIUtility.PingObject(go); } EditorGUILayout.EndHorizontal(); }
void OnEnable() { if (UnityCamera != null) { UpdateCameraMatrix(); } else { this.camera.enabled = false; } if (!viewportClippingEnabled) // the main camera can't display rect inst = this; if (allCameras.IndexOf(this) == -1) { allCameras.Add(this); } }
void Start() { cam = camera.GetComponent <tk2dCamera> (); zoomFactor = originaCamZoom; }
void Awake() { if(instance != null) { Destroy(this.gameObject); return; } instance = this; cam = GetComponent<tk2dCamera>(); CourseHandler.OnActionBegin += HandleOnActionBegin; CourseHandler.OnActionEnd += HandleOnActionEnd; CourseHandler.OnPlacementBegin += HandleOnPlacementBegin; CourseHandler.OnPlacementEnd += HandleOnPlacementEnd; CourseHandler.OnHoleBegin += ResetCamera; }
Vector2 GetScaleForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float width, float height) { Vector2 scale = Vector2.one; float s = 1.0f; if (currentOverride == null) { return(scale); } switch (currentOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfect: s = 1; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = height / settings.nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = width / settings.nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo: float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight; float currentAspect = width / height; if (currentAspect < nativeAspect) { s = width / settings.nativeResolutionWidth; } else { s = height / settings.nativeResolutionHeight; } if (currentOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo) { if (s > 1.0f) { s = Mathf.Floor(s); // round number } else { s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentOverride.scale; scale.Set(s, s); break; } return(scale); }