Inheritance: MonoBehaviour
    // Use this for initialization
    void Start()
    {
        // Script References
        shipGraphics = GetComponent<ShipGraphics>();
        shipPhysicsScript = GetComponent<ShipPhysicsScript>();

        // Component Variables
        cam = GetComponentInChildren<Camera>();
        body = GetComponent<Rigidbody>();
        model = transform.Find("Model").gameObject;
        capsuleCollider = GetComponentInChildren<CapsuleCollider>();
        boxCollider = GetComponentInChildren<BoxCollider>();
        lockSound = GetComponent<AudioSource>();

        // Control Variables
        mouseSensitivity = 8.0f;
        //mouseThreshold = 8.0f;
        //buttonSensitivity = 0.05f;
        //buttonThreshold = 0.05f;

        horTranslation = 0.0f;
        verTranslation = 0.0f;

        enemyNoLock = (Material)Resources.Load("Crosshair");
        enemyLock = (Material)Resources.Load("Crosshair_Enemy");

        trackedObject = null;
        trackingResults = null;
        shootWaitTime = 0.0f;
        targetTime = 0.0f;
        hits = 0;
    }
Esempio n. 2
1
 protected override void InternalDraw(GameTime time, Matrix absoluteTransform, PrimitiveBatch primitiveBatch, Camera camera)
 {
     if (_mesh != null)
     {
         primitiveBatch.DrawMesh(_mesh, absoluteTransform, camera);
     }
 }
Esempio n. 3
0
	//in update - static local scale of gfx and var of x 
	//which is changes over time in update

	void Start () {
		startTimer = false;
		cam = GetComponent<Camera>();
		EndScreen.SetActive(false);
		EndScreenIsActive = false;
		EnableBoxClicks = false;
		playDeathSound = false;
		
		level = 1;
		genLevel(level);

		colors[0] = blue;	
		colors[1] = green;
		colors[2] = orange;
		colors[3] = orange2;
		colors[4] = gray;
		colors[5] = purple;
		colors[6] = red;
		
		

		cam.backgroundColor = colors[Random.Range(0, colors.Length)];

		// Set new BG color at very first start of game
		//cam.backgroundColor = Random.Range(;
		if(Social.localUser.authenticated){
		Social.ReportScore(AddPoints.HighScoreEasy,"",(bool success) => {
		});
		Social.ReportScore(AddPoints.HighScoreNorm,"",(bool success) => {
		});
		Social.ReportScore(AddPoints.HighScoreHard,"",(bool success) => {
		});
		}
	}
Esempio n. 4
0
 public void Start() {
   palletCamera = Camera.main;
   towerCostText = GetComponentInChildren<Text>();
   transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
   towerCostText.transform.SetParent(transform);
   towerCostText.transform.localPosition = new Vector3(palletTextOffset, 0f, 0f);
 }
    void Awake()
    {
        if (camera==null) {
            Debug.LogError("SetupForGrassRendering script (at "+gameObject.name+") - can't find camera component !");
            return;
        }

        if ((useCustomDepthShader) && (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth))) {
            shad=Shader.Find("GrassRenderDepth"); // our simple depth rendering shader (rely on native z-depth buffer and don't render into color channels)
        } else {
            shad=Shader.Find("Hidden/Camera-DepthTexture"); // unity's render depth - probably slower as it renders everything into color buffer
        }
        if (!shad) {
            // we've got no shader ? Make simple one (handles native z-buffer for Opaque RenderType only)
            Material mat=new Material("Shader \"RenderDepth\" {SubShader { Tags { \"RenderType\"=\"Opaque\"} \n Pass { ColorMask 0 }}}");
            shad=mat.shader;
        }
        SetupTexture();
        GameObject go=new GameObject("GrassDepthCamera");
        go.AddComponent(typeof(Camera));
        go.transform.parent=transform;
        myCam=go.camera;
        SetupParams();

        teleportTresholdSqr = teleportTreshold * teleportTreshold;
    }
Esempio n. 6
0
        public override void Load()
        {
            camera = ((Camera)Container);

            SlimDX.RawInput.Device.RegisterDevice(SlimDX.Multimedia.UsagePage.Generic, SlimDX.Multimedia.UsageId.Mouse, SlimDX.RawInput.DeviceFlags.None);
            SlimDX.RawInput.Device.MouseInput += new EventHandler<MouseInputEventArgs>(MouseEventHandle);
        }
Esempio n. 7
0
 void Awake()
 {
     mainCamera = Camera.main;
     if (s_Instance == null)
         s_Instance = this;
     //DontDestroyOnLoad(this);
 }
Esempio n. 8
0
	// Update is called once per frame
	void Update ()
    {
	    if(fpCamera == null)
        {
            fpCamera = GameObject.FindGameObjectWithTag("aiAgent").GetComponent<AI_AGENT_CONTROLLER>().getCamera();
        }
        if(Input.GetMouseButtonDown(1))
        {
            Vector3 newObjectPosition = getMouseGrid();
            switch(nodeType)
            {
                case 0:
                    createWall(newObjectPosition);
                    break;
                case 1:
                    createRoad(newObjectPosition);
                    break;
                case 2:
                    createForest(newObjectPosition);
                    break;
                default:
                    Debug.Log("ERROR: OBJECT NOT SELECTED");
                    break;
            }
            AI_AGENT_CONTROLLER player = fpCamera.transform.parent.gameObject.GetComponent<AI_AGENT_CONTROLLER>();
            player.restart();
        }
	}
Esempio n. 9
0
 protected override void Start()
 {
     base.Start ();
     controller = GetComponent<PlayerController> ();
     gunController = GetComponent<GunController> ();
     viewCamera = Camera.main;
 }
Esempio n. 10
0
    Texture2D Capture(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

        return screenShot;
    }
Esempio n. 11
0
            public TileMap3D(GraphicsDevice graphicsDevice, ContentManager contentManager, int width, int height)
            {
                this.GraphicsDevice = graphicsDevice;
                Wall = contentManager.Load<Model>("Models/TileMap3D/Wall");
                FloorTile = contentManager.Load<Model>("Models/TileMap3D/FloorTile");
                Dirt = contentManager.Load<Model>("Models/TileMap3D/Dirt");
                Cleaner = contentManager.Load<Model>("Models/TileMap3D/Cleaner");

                ((BasicEffect)Wall.Meshes[0].Effects[0]).EnableDefaultLighting();
                ((BasicEffect)FloorTile.Meshes[0].Effects[0]).EnableDefaultLighting();
                ((BasicEffect)Dirt.Meshes[0].Effects[0]).EnableDefaultLighting();
                ((BasicEffect)Cleaner.Meshes[0].Effects[0]).EnableDefaultLighting();
                foreach (BasicEffect effect in Cleaner.Meshes[0].Effects)
                    effect.Tag = effect.DiffuseColor;
                foreach (BasicEffect effect in FloorTile.Meshes[0].Effects)
                    effect.Tag = effect.DiffuseColor;

                dss.DepthBufferEnable = true;
                dss.DepthBufferFunction = CompareFunction.LessEqual;
                dss.DepthBufferWriteEnable = true;
                rs.CullMode = CullMode.CullCounterClockwiseFace;
                ss.AddressU = TextureAddressMode.Wrap;
                ss.AddressV = TextureAddressMode.Wrap;
                ss.Filter = TextureFilter.Anisotropic;

                Camera = new Camera(graphicsDevice.Viewport.AspectRatio, graphicsDevice);
            }
Esempio n. 12
0
 void Awake()
 {
     cam = Camera.main;
     myTransform = transform;
     SpriteRenderer sRenderer = GetComponent<SpriteRenderer> (); //grabs sprite renderer from engine
     spriteWidth = sRenderer.sprite.bounds.size.x;				//get width of screen
 }
Esempio n. 13
0
        public FormLoadTexture()
        {
            InitializeComponent();

            //if (CameraDictionary.Instance.ContainsKey(this.GetType().Name))
            //{
            //    this.camera = CameraDictionary.Instance[this.GetType().Name];
            //}
            //else
            {
                this.camera = new Camera(CameraType.Ortho, this.glCanvas1.Width, this.glCanvas1.Height);
                //CameraDictionary.Instance.Add(this.GetType().Name, this.camera);
            }

            rotator = new SatelliteRotator(this.camera);
            this.glCanvas1.MouseWheel += glCanvas1_MouseWheel;

            element = new LoadTextureExample();
            element.Initialize();

            IUILayoutParam param = new IUILayoutParam(
                AnchorStyles.Left | AnchorStyles.Bottom,
                new Padding(10, 10, 10, 10), new Size(50, 50));
            uiAxis = new SimpleUIAxis(param);
            uiAxis.Initialize();

            this.glCanvas1.MouseWheel += glCanvas1_MouseWheel;
            this.glCanvas1.KeyPress += glCanvas1_KeyPress;
            this.glCanvas1.MouseDown += glCanvas1_MouseDown;
            this.glCanvas1.MouseMove += glCanvas1_MouseMove;
            this.glCanvas1.MouseUp += glCanvas1_MouseUp;
            this.glCanvas1.OpenGLDraw += glCanvas1_OpenGLDraw;
            this.glCanvas1.Resize += glCanvas1_Resize;
            this.Load += Form_Load;
        }
Esempio n. 14
0
    void OnEnable()
    {
        if (blitMaterial == null)
            blitMaterial = new Material(Shader.Find("Custom/SteamVR_BlitFlip"));

        camera = GetComponent<Camera>();
    }
Esempio n. 15
0
	public void OnCloseClick()
	{
		Time.timeScale = 1;
		c = GameObject.FindGameObjectWithTag("MainCamera").camera;
		GameObject player = c.transform.parent.gameObject;

		AudioSource log = GameObject.FindGameObjectWithTag("AudioLog").GetComponent<AudioSource>();
		AudioSource music = GameObject.FindGameObjectWithTag("Music").GetComponent<AudioSource>();

		//if(log.isPlaying)
		//	log.Stop();

		//music.volume = PlayerPrefs.GetFloat("MusicVol");

		MouseLook cml = c.GetComponent<MouseLook>();
		MouseLook pml = player.GetComponent<MouseLook>();
		CharacterMover pcm = player.GetComponent<CharacterMover>();
		CameraBob pcb = player.GetComponent<CameraBob>();
		MouseController mc = player.GetComponent<MouseController>();


		cml.enabled = true;
		pml.enabled = true;
		pcm.enabled = true;
		pcb.enabled = true;
		mc.enabled = true;
		mc.interactLabel.enabled = true;
		mc.interactLabel.GetComponentInChildren<UISprite>().enabled = true;
		Screen.showCursor = false;
		Screen.lockCursor = true;

		NGUITools.SetActive(this.gameObject, false);
	}
    // Use this for initialization
    void Start()
    {
        camera = Camera.main;
        Joueur Joueur1 = GameStarter.obtenirJoueur1(); //player
        Joueur Ordi= GameStarter.obtenirJoueur2(); // IA
        MyControler = new RuleController();
        MyControler.demarerDuel(Joueur1, Ordi);
        this.DisplayHand();
        //GameObject PlayedCard = this.transform.GetChild(0).gameObject;
        //GameObject slot1 = PlayedCard.transform.GetChild(3).gameObject;
        //Vector3 positions = slot1.transform.position;

        //GameObject cardClone = (GameObject)Instantiate(test, positions,slot1.transform.rotation);
        //cardClone.transform.parent = PlayedCard.transform;
        ////Quaternion quat = new Quaternion(0, 0, 0, 0);
        //positions = positions + new Vector3(0f, 1f, 0f);

        ////positions.z = -1;

        ////positions.z = -1;
        //////cardClone.transform.position = slot1.transform.position;
        //cardClone.transform.rotation = slot1.transform.rotation;

        //Debug.Log(positions);
        //cardClone.transform.localScale = slot1.transform.localScale;
        //cardClone.transform.position = positions;
        //Debug.Log(cardClone.transform.position);

        //PlayedCard.gameObject.AddComponent();
        //Debug.Log(cardClone.transform.localScale);
    }
Esempio n. 17
0
  public Curve(Molecule mol, Vector2 pos, Camera VectroCam = null)
  {
    _mol = mol;
    _label = mol.getName();
    _points = new LinkedList<Vector2>();
    //_pts = new Vector2[_maxPoints];
    _pts = new List<Vector2>();
    _minY = 0;
    _maxY = 0;
    _color = new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f));
    //_line = new VectorLine(mol.getName(), _pts, _color, null, 2.0f, LineType.Continuous, Joins.Weld);
    _line = new VectorLine(mol.getName(), _pts, 2.0f, LineType.Continuous, Joins.Weld);
    _line.color = _color;
    _isEnabled = true;
    _vectroCam = VectroCam;
//     _pos = pos;

//     _lines = new VectorLine[_maxPoints];
//     _linesTypes = new _linesTypes[_maxPoints - 1];

    VectorManager.useDraw3D = true;
    if (_vectroCam != null)
      //Vectrosity.VectorLine.SetCamera(_vectroCam);
      Vectrosity.VectorLine.SetCamera3D(_vectroCam);
    else
      Logger.Log("No Camera set for the Graph Window.", Logger.Level.ERROR);
  }
 void Awake()
 {
     state = state;
     this.MainCamera = GameObject.Find("Main Camera").camera;
     enemy = GameObject.Find("Enemy");
     InputManager = GameObject.Find("InputManager");
 }
Esempio n. 19
0
    // Use this for initialization
    void Start()
    {
        MessageCenter.Instance.RegisterListener(MessageType.PlayerKilled, HandleTreeDeath);

        cam = GetComponent<Camera>();
        KillCamera = cam;
    }
    public virtual void Initialize()
    {
        //can't do anything else if we don't have PlayerInfo resources loaded!
        m_myPlayerInfo = m_nvs.myInfo;
        if (m_myPlayerInfo.cartGameObject == null || m_myPlayerInfo.ballGameObject == null) return;

        //also make sure we can get the player camera
        m_myCamera = Camera.main;
        if (m_myCamera == null) return;

        //get info from all players
        m_players = new List<PlayerInfo>();

        //we don't want to use foreachs, for collection iteration errors on disconnect scenarios
        for (int i = 0; i < m_nvs.players.Count; i++) {
            PlayerInfo player = (PlayerInfo)m_nvs.players[i];
            if (player != null) {
                // do NOT want to include the player himself
                if (player != m_myPlayerInfo) {
                    m_players.Add(player);
                }
            }
        }

        m_initialized = true;
    }
Esempio n. 21
0
    // Use this for initialization
    void Start()
    {
        // カメラを列挙する
        // 使いたいカメラのインデックスをVideoIndexに入れる
        // 列挙はUnityで使うのはOpenCVだけど、インデックスは同じらしい
        var devices = WebCamTexture.devices;
        for ( int i = 0; i < devices.Length; i++ ) {
            print( string.Format( "index {0}:{1}", i, devices[i].name) );
        }

        // ビデオの設定
        video = new VideoCapture( VideoIndex );
        video.Set( CaptureProperty.FrameWidth, Width );
        video.Set( CaptureProperty.FrameHeight, Height );

        print( string.Format("{0},{1}", Width, Height) );

        // 顔検出器の作成
        cascade = new CascadeClassifier( Application.dataPath + @"/haarcascade_frontalface_alt.xml" );

        // テクスチャの作成
        texture = new Texture2D( Width, Height, TextureFormat.RGB24, false );
        renderer.material.mainTexture = texture;

        // 変換用のカメラの作成
        _Camera = GameObject.Find( Camera.name ).camera;
        print( string.Format( "({0},{1})({2},{3})", Screen.width, Screen.height, _Camera.pixelWidth, _Camera.pixelHeight ) );
    }
Esempio n. 22
0
 public void Init(Camera controlCamera)
 {
     State = StateEnum.Idle;
     HideUI();
     _controlCamera = controlCamera;
     enabled = true;
 }
Esempio n. 23
0
    ///////////////////////////////////////////////////////////////////////////////
    // functions
    ///////////////////////////////////////////////////////////////////////////////

    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    override protected float CalculateDepth ( Camera _cam ) {
        if ( _cam == null )
            return 0.0f;
        float dist = _cam.farClipPlane - _cam.nearClipPlane;
        float unitLayer = dist/MAX_LAYER;
        return -(((float)layer_ + bias_) * unitLayer - _cam.transform.position.y + _cam.nearClipPlane);
    }
 private void Form_Load(object sender, EventArgs e)
 {
     {
         var camera = new Camera(
             new vec3(0, 0, 5), new vec3(0, 0, 0), new vec3(0, 1, 0),
             CameraType.Perspecitive, this.glCanvas1.Width, this.glCanvas1.Height);
         var rotator = new SatelliteManipulater();
         rotator.Bind(camera, this.glCanvas1);
         rotator.BindingMouseButtons = System.Windows.Forms.MouseButtons.Left | System.Windows.Forms.MouseButtons.Right;
         this.rotator = rotator;
         this.scene = new Scene(camera, this.glCanvas1);
         this.glCanvas1.Resize += this.scene.Resize;
     }
     {
         Teapot model = new Teapot();
         OrderDependentTransparencyRenderer renderer = OrderDependentTransparencyRenderer.Create(model, model.Size, Teapot.strPosition, Teapot.strColor);
         SceneObject obj = renderer.WrapToSceneObject();
         this.scene.RootObject.Children.Add(obj);
     }
     {
         var builder = new StringBuilder();
         builder.AppendLine("1: Scene's property grid.");
         builder.AppendLine("2: Canvas' property grid.");
         MessageBox.Show(builder.ToString());
     }
 }
        public override void Update(float elapsed, Camera camera, Player player, Map map)
        {
            base.Update (elapsed, camera, player, map);
            if (!dead) {
                tileDirRelSprites = new List<TileDirectionRelSprite> ();
                ApplyCamera (camera);
                x += xDir * MOVE_SPEED * elapsed;
                y += yDir * FALL_SPEED * elapsed;
                if (jumping) {
                    if (yDir >= 0) {
                        jumping = false;
                        falling = true;
                    } else {
                        yDir += FALL_SPEED;
                    }
                } else if (falling) {
                    if (yDir < FALL_CAP)
                        yDir += FALL_SPEED;
                }
                gun.Update (elapsed, camera);
                if (xDir != 0) {
                    gun.left = xDir < 0;

                }
                if (gun.left) {
                    gun.x = x - gun.width;
                } else if (!gun.left) {
                    gun.x = x + width;
                }
                gun.y = y + height / 3;
            }
        }
Esempio n. 26
0
 public void Init(Transform dependence, string msg, Color textColor, FlyNumerDirection flyDir = FlyNumerDirection.side,int size = 42)
 {
     base.Init();
     cam = MainController.Instance.MainCamera;
     this.dependence = dependence;
     incFlyingNumbers.Init(msg, textColor, flyDir, size, OnDead);
 }
Esempio n. 27
0
 public void Draw(SpriteBatch spriteBatch, Camera cam, Texture2D texture)
 {
     for (int i = 0; i < MaxParticles; i++)
         {
             sparkParticles[i].Draw(spriteBatch, cam, texture, gameWindow);
         }
 }
    // Use this for initialization
    void Awake()
    {
        GameObject go = new GameObject("depthCamera");
        depthCamera = go.AddComponent<Camera>();
        depthCamera.transform.position = Vector3.zero;
        depthCamera.transform.rotation = transform.rotation;
        depthCamera.transform.localPosition += transform.forward * Near;
        depthCamera.transform.parent = transform;
        depthCamera.isOrthoGraphic = true;

        depthCamera.clearFlags = CameraClearFlags.SolidColor;
        depthCamera.backgroundColor = Color.white;
        depthTexture = new RenderTexture(TextureSize,TextureSize, 16, RenderTextureFormat.ARGB32);
        depthTexture.filterMode = FilterMode.Point;
        depthCamera.targetTexture = depthTexture;
        depthCamera.SetReplacementShader(shader, null);
        depthCamera.enabled = false;
        biasMatrix = Matrix4x4.identity;
        biasMatrix[ 0, 0 ] = 0.5f;
        biasMatrix[ 1, 1 ] = 0.5f;
        biasMatrix[ 2, 2 ] = 0.5f;
        biasMatrix[ 0, 3 ] = 0.5f;
        biasMatrix[ 1, 3 ] = 0.5f;
        biasMatrix[ 2, 3 ] = 0.5f;
    }
Esempio n. 29
0
    // Use this for initialization
    public void OnClick()
    {
        mainCam = FindObjectOfType<Camera>();

        if (mainCam.GetComponent<GameScript>().state.Equals("stand"))
            mainCam.GetComponent<GameScript>().state = "right";
    }
Esempio n. 30
0
        void renderTargetUserControl1_Render( RenderTargetUserControl sender, Camera camera )
        {
            //update camera
            if( Map.Instance != null )
            {
                Vec3 position;
                Vec3 forward;
                Degree fov;

                MapCamera mapCamera = Entities.Instance.GetByName( "MapCamera_1" ) as MapCamera;
                if( mapCamera != null )
                {
                    position = mapCamera.Position;
                    forward = mapCamera.Rotation * new Vec3( 1, 0, 0 );
                    fov = mapCamera.Fov;
                }
                else
                {
                    position = Map.Instance.EditorCameraPosition;
                    forward = Map.Instance.EditorCameraDirection.GetVector();
                    fov = Map.Instance.Fov;
                }

                if( fov == 0 )
                    fov = Map.Instance.Fov;

                renderTargetUserControl1.CameraNearFarClipDistance = Map.Instance.NearFarClipDistance;
                renderTargetUserControl1.CameraFixedUp = Vec3.ZAxis;
                renderTargetUserControl1.CameraFov = fov;
                renderTargetUserControl1.CameraPosition = position;
                renderTargetUserControl1.CameraDirection = forward;
            }
        }
Esempio n. 31
0
 private static void SoundSource_DebugRender(SoundSource.orig_DebugRender orig, Celeste.SoundSource self, Camera camera)
 {
     if (!Settings.ShowHitboxes)
     {
         orig(self, camera);
     }
 }
Esempio n. 32
0
 //
 // Summary:
 //     ///
 //     Obtains the direction vector from the camera to a position
 //     ///
 //
 // Parameters:
 //   position:
 //     The point to determine the direction to.
 //  
 public static Vector3 DirectionToPosition(this Camera camera, Vector3 position) {
     Vector3 direction = position - camera.transform.position;
     direction.Normalize();
     return direction;
 }
Esempio n. 33
0
        public void Initialize(Assets assets, Camera sceneLogicCamera)
        {
            _assets = assets;

            CreateGUI(sceneLogicCamera);
        }
Esempio n. 34
0
        /// <summary>
        /// Creates the GUI for the default editor
        /// </summary>
        /// <param name="sceneLogicCamera"></param>
        private void CreateGUI(Camera sceneLogicCamera)
        {
            GuiCanvas = new GUICanvas(Vector2.Zero, new Vector2(GameSettings.g_screenwidth, GameSettings.g_screenheight));

            defaultStyle = new GUIStyle(
                dimensionsStyle: new Vector2(200, 35),
                textFontStyle: _assets.MonospaceFont,
                blockColorStyle: Color.Gray,
                textColorStyle: Color.White,
                sliderColorStyle: Color.White,
                guiAlignmentStyle: GUIStyle.GUIAlignment.None,
                textAlignmentStyle: GUIStyle.TextAlignment.Left,
                textButtonAlignmentStyle: GUIStyle.TextAlignment.Center,
                textBorderStyle: new Vector2(10, 1),
                parentDimensionsStyle: GuiCanvas.Dimensions);

            //Editor gizmo control!
            GuiCanvas.AddElement(_leftSideList = new GUIList(Vector2.Zero, defaultStyle));

            _leftSideList.AddElement(_gizmoTranslation = new GUITextBlockButton(defaultStyle, "Translate (T)")
            {
                ButtonObject     = this,
                ButtonMethod     = GetType().GetMethod("ChangeGizmoMode"),
                ButtonMethodArgs = new object[] { EditorLogic.GizmoModes.Translation },
            });
            _leftSideList.AddElement(_gizmoRotation = new GUITextBlockButton(defaultStyle, "Rotate (R)")
            {
                ButtonObject     = this,
                ButtonMethod     = GetType().GetMethod("ChangeGizmoMode"),
                ButtonMethodArgs = new object[] { EditorLogic.GizmoModes.Rotation },
            });
            _leftSideList.AddElement(_gizmoScale = new GUITextBlockButton(defaultStyle, "Scale (Z)")
            {
                ButtonObject     = this,
                ButtonMethod     = GetType().GetMethod("ChangeGizmoMode"),
                ButtonMethodArgs = new object[] { EditorLogic.GizmoModes.Scale },
            });
            _leftSideList.AddElement(new GUITextBlockToggle(defaultStyle, "Local: ")
            {
                ToggleField = typeof(GameStats).GetField("e_LocalTransformation"),
                Toggle      = GameStats.e_LocalTransformation
            });
            _leftSideList.Alignment = GUIStyle.GUIAlignment.BottomLeft;

            ChangeGizmoMode(EditorLogic.GizmoModes.Translation);

            //Editor options
            GuiCanvas.AddElement(_rightSideList = new GuiListToggleScroll(new Vector2(-20, 0), defaultStyle));

            GUITextBlock helperText = new GUITextBlock(new Vector2(0, 100), new Vector2(300, 200), CreateHelperText(), defaultStyle.TextFontStyle, new Color(Color.DimGray, 0.2f), Color.White, GUIStyle.TextAlignment.Left, new Vector2(10, 1))
            {
                IsHidden = true
            };

            GuiCanvas.AddElement(helperText);

            _rightSideList.AddElement(new GUITextBlockToggle(defaultStyle, "Enable Editor")
            {
                ToggleField = typeof(GameStats).GetField("e_EnableSelection"),
                Toggle      = GameStats.e_EnableSelection
            });

            _rightSideList.AddElement(new GUITextBlockToggle(defaultStyle, "Highlight Meshes")
            {
                ToggleField = typeof(GameSettings).GetField("e_drawoutlines"),
                Toggle      = GameSettings.e_drawoutlines
            });

            _rightSideList.AddElement(new GUITextBlockToggle(defaultStyle, "Show Controls")
            {
                ToggleProperty = typeof(GUITextBlock).GetProperty("IsVisible"),
                ToggleObject   = helperText,
                Toggle         = helperText.IsVisible
            });

            _rightSideList.AddElement(new GUITextBlockToggle(defaultStyle, "Default Material")
            {
                ToggleField = typeof(GameSettings).GetField("d_defaultmaterial"),
                Toggle      = GameSettings.d_defaultmaterial
            });

            _rightSideList.AddElement(new GuiSliderFloatText(defaultStyle, 0.1f, 3 /*(float) (Math.PI - 0.1)*/, 2, "Field Of View: ")
            {
                SliderObject   = sceneLogicCamera,
                SliderProperty = typeof(Camera).GetProperty("FieldOfView"),
                SliderValue    = sceneLogicCamera.FieldOfView
            });

            //_rightSideList.AddElement(new GuiDropList(defaultStyle, "Show: ")
            //{
            //});

            _rightSideList.AddElement(new GUITextBlock(defaultStyle, "Selection")
            {
                BlockColor = Color.DimGray, Dimensions = new Vector2(200, 10), TextAlignment = GUIStyle.TextAlignment.Center
            });

            GuiListToggle _selectionList = new GuiListToggle(Vector2.Zero, defaultStyle);

            _objectDescriptionList = new GUIList(Vector2.Zero, defaultStyle);

            _objectDescriptionList.AddElement(_objectDescriptionName = new GUITextBlock(defaultStyle, "objDescName"));
            _objectDescriptionList.AddElement(_objectDescriptionPos  = new GUITextBlock(defaultStyle, "objDescName"));
            _objectDescriptionList.AddElement(_objectButton1         = new GUITextBlockButton(defaultStyle, "objButton1")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectToggle0 = new GUITextBlockToggle(defaultStyle, "objToggle0")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectToggle1 = new GUITextBlockToggle(defaultStyle, "objToggle1")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectToggle2 = new GUITextBlockToggle(defaultStyle, "objToggle2")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectSlider0 = new GuiSliderFloatText(defaultStyle, 0, 1, 2, "objToggle1")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectSlider1 = new GuiSliderFloatText(defaultStyle, 0, 1, 2, "objToggle2")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectSlider2 = new GuiSliderIntText(defaultStyle, 0, 10, 1, "objToggle3")
            {
                IsHidden = true
            });
            _objectDescriptionList.AddElement(_objectColorPicker1 = new GUIColorPicker(defaultStyle)
            {
                IsHidden = true
            });

            _selectionList.AddElement(_objectDescriptionList);
            _rightSideList.AddElement(_selectionList);

            /////////////////////////////////////////////////////////////////
            //Options
            /////////////////////////////////////////////////////////////////

            _rightSideList.AddElement(new GUITextBlock(defaultStyle, "Options")
            {
                BlockColor = Color.DimGray, Dimensions = new Vector2(200, 10), TextAlignment = GUIStyle.TextAlignment.Center
            });

            GuiListToggle optionList = new GuiListToggle(Vector2.Zero, defaultStyle);

            _rightSideList.AddElement(optionList);

            /////////////////////////////////////////////////////////////////
            //Post Processing
            /////////////////////////////////////////////////////////////////

            optionList.AddElement(new GUITextBlock(defaultStyle, "PostProcessing")
            {
                BlockColor = Color.DarkSlateGray, Dimensions = new Vector2(200, 10), TextAlignment = GUIStyle.TextAlignment.Center
            });

            GuiListToggle postprocessingList = new GuiListToggle(Vector2.Zero, defaultStyle)
            {
                ToggleBlockColor = Color.DarkSlateGray, IsToggled = false
            };

            optionList.AddElement(postprocessingList);

            postprocessingList.AddElement(new GUITextBlockToggle(defaultStyle, "Temporal AA")
            {
                ToggleField = typeof(GameSettings).GetField("g_taa"),
                Toggle      = GameSettings.g_taa
            });

            postprocessingList.AddElement(new GUITextBlockToggle(defaultStyle, "Tonemap TAA")
            {
                ToggleField = typeof(GameSettings).GetField("g_taa_tonemapped"),
                Toggle      = GameSettings.g_taa_tonemapped
            });

            postprocessingList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 4, 2, "WhitePoint: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("WhitePoint"),
                SliderValue    = GameSettings.WhitePoint
            });

            postprocessingList.AddElement(new GuiSliderFloatText(defaultStyle, -8, 8, 2, "Exposure: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("Exposure"),
                SliderValue    = GameSettings.Exposure
            });

            postprocessingList.AddElement(new GuiSliderFloatText(defaultStyle, -1, 1, 2, "S-Curve: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("SCurveStrength"),
                SliderValue    = GameSettings.SCurveStrength
            });

            postprocessingList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 1, 2, "Chr. Abb.: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("ChromaticAbberationStrength"),
                SliderValue    = GameSettings.ChromaticAbberationStrength
            });

            postprocessingList.AddElement(new GUITextBlockToggle(defaultStyle, "Color Grading")
            {
                ToggleField = typeof(GameSettings).GetField("g_ColorGrading"),
                Toggle      = GameSettings.g_ColorGrading
            });

            /////////////////////////////////////////////////////////////////
            //SSR
            /////////////////////////////////////////////////////////////////

            optionList.AddElement(new GUITextBlock(Vector2.Zero, new Vector2(200, 10), "Screen Space Reflections",
                                                   defaultStyle.TextFontStyle, Color.DarkSlateGray, Color.White, GUIStyle.TextAlignment.Center,
                                                   Vector2.Zero));

            GuiListToggle ssrList = new GuiListToggle(Vector2.Zero, defaultStyle)
            {
                ToggleBlockColor = Color.DarkSlateGray, IsToggled = false
            };

            optionList.AddElement(ssrList);

            ssrList.AddElement(new GUITextBlockToggle(defaultStyle, "Enable SSR")
            {
                ToggleProperty = typeof(GameSettings).GetProperty("g_SSReflection"),
                Toggle         = GameSettings.g_SSReflection
            });

            ssrList.AddElement(new GUITextBlockToggle(defaultStyle, "Stochastic distr.")
            {
                ToggleProperty = typeof(GameSettings).GetProperty("g_SSReflectionTaa"),
                Toggle         = GameSettings.g_SSReflectionTaa
            });

            ssrList.AddElement(new GUITextBlockToggle(defaultStyle, "Temporal Noise")
            {
                ToggleField = typeof(GameSettings).GetField("g_SSReflectionNoise"),
                Toggle      = GameSettings.g_SSReflectionNoise
            });

            ssrList.AddElement(new GUITextBlockToggle(defaultStyle, "Firefly Reduction")
            {
                ToggleProperty = typeof(GameSettings).GetProperty("g_SSReflection_FireflyReduction"),
                Toggle         = GameSettings.g_SSReflection_FireflyReduction
            });

            ssrList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 5, 2, "Firefly Threshold ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("g_SSReflection_FireflyThreshold"),
                SliderValue    = GameSettings.g_SSReflection_FireflyThreshold
            });

            ssrList.AddElement(new GuiSliderIntText(defaultStyle, 1, 100, 1, "Samples: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("g_SSReflections_Samples"),
                SliderValue    = GameSettings.g_SSReflections_Samples
            });

            ssrList.AddElement(new GuiSliderIntText(defaultStyle, 1, 100, 1, "Search Samples: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("g_SSReflections_RefinementSamples"),
                SliderValue    = GameSettings.g_SSReflections_RefinementSamples
            });

            /////////////////////////////////////////////////////////////////
            //SSAO
            /////////////////////////////////////////////////////////////////
            ///
            optionList.AddElement(new GUITextBlock(Vector2.Zero, new Vector2(200, 10), "Ambient Occlusion",
                                                   defaultStyle.TextFontStyle, Color.DarkSlateGray, Color.White, GUIStyle.TextAlignment.Center,
                                                   Vector2.Zero));

            GuiListToggle ssaoList = new GuiListToggle(Vector2.Zero, defaultStyle)
            {
                ToggleBlockColor = Color.DarkSlateGray, IsToggled = false
            };

            optionList.AddElement(ssaoList);

            ssaoList.AddElement(new GUITextBlockToggle(defaultStyle, "Enable SSAO")
            {
                ToggleProperty = typeof(GameSettings).GetProperty("g_ssao_draw"),
                Toggle         = GameSettings.g_ssao_draw
            });

            ssaoList.AddElement(new GUITextBlockToggle(defaultStyle, "SSAO Blur: ")
            {
                ToggleField = typeof(GameSettings).GetField("g_ssao_blur"),
                Toggle      = GameSettings.g_ssao_blur
            });

            ssaoList.AddElement(new GuiSliderIntText(defaultStyle, 1, 32, 1, "SSAO Samples: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("g_ssao_samples"),
                SliderValue    = GameSettings.g_ssao_samples
            });

            ssaoList.AddElement(new GuiSliderFloatText(defaultStyle, 1, 100, 2, "Sample Radius: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("g_ssao_radius"),
                SliderValue    = GameSettings.g_ssao_radius
            });

            ssaoList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 4, 1, "SSAO Strength: ")
            {
                SliderProperty = typeof(GameSettings).GetProperty("g_ssao_strength"),
                SliderValue    = GameSettings.g_ssao_strength
            });

            /////////////////////////////////////////////////////////////////
            //Bloom
            /////////////////////////////////////////////////////////////////
            ///
            optionList.AddElement(new GUITextBlock(Vector2.Zero, new Vector2(200, 10), "Bloom",
                                                   defaultStyle.TextFontStyle, Color.DarkSlateGray, Color.White, GUIStyle.TextAlignment.Center,
                                                   Vector2.Zero));

            GuiListToggle bloomList = new GuiListToggle(Vector2.Zero, defaultStyle)
            {
                ToggleBlockColor = Color.DarkSlateGray, IsToggled = false
            };

            optionList.AddElement(bloomList);

            bloomList.AddElement(new GUITextBlockToggle(defaultStyle, "Enable Bloom")
            {
                ToggleField = typeof(GameSettings).GetField("g_BloomEnable"),
                Toggle      = GameSettings.g_BloomEnable
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 4, 1, "Threshold: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomThreshold"),
                SliderValue = GameSettings.g_BloomThreshold
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP0 Radius: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomRadius1"),
                SliderValue = GameSettings.g_BloomRadius1
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP0 Strength: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomStrength1"),
                SliderValue = GameSettings.g_BloomStrength1
            });


            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP1 Radius: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomRadius2"),
                SliderValue = GameSettings.g_BloomRadius2
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP1 Strength: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomStrength2"),
                SliderValue = GameSettings.g_BloomStrength2
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP2 Radius: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomRadius3"),
                SliderValue = GameSettings.g_BloomRadius3
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP2 Strength: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomStrength3"),
                SliderValue = GameSettings.g_BloomStrength3
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP3 Radius: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomRadius4"),
                SliderValue = GameSettings.g_BloomRadius4
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP3 Strength: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomStrength4"),
                SliderValue = GameSettings.g_BloomStrength4
            });


            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP4 Radius: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomRadius5"),
                SliderValue = GameSettings.g_BloomRadius5
            });

            bloomList.AddElement(new GuiSliderFloatText(defaultStyle, 0, 8, 1, "MIP4 Strength: ")
            {
                SliderField = typeof(GameSettings).GetField("g_BloomStrength5"),
                SliderValue = GameSettings.g_BloomStrength5
            });

            _rightSideList.Alignment = GUIStyle.GUIAlignment.TopRight;
        }
 private void BroadcastChange(Camera camera) {
     if (camera == null) { return; } // should not happen, throw error
     if (CameraChanged != null) {
         CameraChanged(camera);
     }
 }
Esempio n. 36
0
 void Start()
 {
     camera        = Camera.main;
     Grid          = new ProcGrid(gridSize);
     previewBlocks = new List <GameObject>();
 }
Esempio n. 37
0
 void Start()
 {
     // シーン開始時にメインカメラのCameraコンポーネントを変数camに取得する
     cam = Camera.main;
 }
Esempio n. 38
0
 //
 // Summary:
 //     ///
 //     Determines if an object is within a cone of visibility of the cameras center point.
 //     NOTE: This doesn't take into account any culling or occlusion that may mean the object is ultimately not visible to the user.
 //     ///
 //
 // Parameters:
 //   gameObject:
 //     The game object to check for being within the cameras view.
 //
 //   angleInDegrees
 //     The maximum angle, in degrees, within which the camera would be considered to be facing the specified object
 //  
 public static bool IsFacingObject(this Camera camera, GameObject gameObject, float angleInDegrees) {
     return camera.IsFacingPosition(gameObject.transform.position, angleInDegrees);
 }
Esempio n. 39
0
 public override void OnEnable() => Component = gameObject.GetComponent <Camera>();
Esempio n. 40
0
 //
 // Summary:
 //     ///
 //     Obtains the direction vector from the camera to an object
 //     ///
 //
 // Parameters:
 //   gameObject:
 //     The game object to determine the direction to.
 //  
 public static Vector3 DirectionToObject(this Camera camera, GameObject gameObject) {
     return camera.DirectionToPosition(gameObject.transform.position);
 }
 public LensDistortionUrpPass(Camera camera, RenderTexture targetTexture)
 {
     lensDistortionCrossPipelinePass = new LensDistortionCrossPipelinePass(camera, targetTexture);
     ConfigureTarget(targetTexture, targetTexture.depthBuffer);
     lensDistortionCrossPipelinePass.Setup();
 }
        private IEnumerator DoRendering(bool forceRenderFullMap = false)
        {
            yield return(new WaitForFixedUpdate());

            if (renderingInt)
            {
                Log.Error("Progress Renderer is still rendering an image while a new rendering was requested. This can lead to missing or wrong data. (This can also happen in rare situations when you trigger manual rendering the exact same time as an automatic rendering happens. If you did that, just check your export folder if both renderings were done corrently and ignore this error.)");
            }
            renderingInt = true;

            // Temporary switch to this map for rendering
            bool switchedMap   = false;
            Map  rememberedMap = Find.CurrentMap;

            if (map != rememberedMap)
            {
                switchedMap             = true;
                Current.Game.CurrentMap = map;
            }

            // Close world view if needed
            bool rememberedWorldRendered = WorldRendererUtility.WorldRenderedNow;

            if (rememberedWorldRendered)
            {
                CameraJumper.TryHideWorld();
            }

            // Calculate rendered area
            float startX = 0;
            float startZ = 0;
            float endX   = map.Size.x;
            float endZ   = map.Size.z;

            if (!forceRenderFullMap)
            {
                List <Designation> cornerMarkers = map.designationManager.allDesignations.FindAll(des => des.def == DesignationDefOf.CornerMarker);
                if (cornerMarkers.Count > 1)
                {
                    startX = endX;
                    startZ = endZ;
                    endX   = 0;
                    endZ   = 0;
                    foreach (Designation des in cornerMarkers)
                    {
                        IntVec3 cell = des.target.Cell;
                        if (cell.x < startX)
                        {
                            startX = cell.x;
                        }
                        if (cell.z < startZ)
                        {
                            startZ = cell.z;
                        }
                        if (cell.x > endX)
                        {
                            endX = cell.x;
                        }
                        if (cell.z > endZ)
                        {
                            endZ = cell.z;
                        }
                    }
                    endX += 1;
                    endZ += 1;
                }
            }

            // Only use smoothing when rendering was not triggered manually
            if (!manuallyTriggered)
            {
                // Test if target render area changed to reset smoothing
                if (rsTargetStartX != startX || rsTargetStartZ != startZ || rsTargetEndX != endX || rsTargetEndZ != endZ)
                {
                    // Check if area was manually reset or uninitialized (-1) to not smooth
                    if (rsTargetStartX == -1f && rsTargetStartZ == -1f && rsTargetEndX == -1f && rsTargetEndZ == -1f)
                    {
                        rsCurrentPosition = 1f;
                    }
                    else
                    {
                        rsCurrentPosition = 1f / (PRModSettings.smoothRenderAreaSteps + 1);
                    }
                    rsOldStartX    = rsTargetStartX;
                    rsOldStartZ    = rsTargetStartZ;
                    rsOldEndX      = rsTargetEndX;
                    rsOldEndZ      = rsTargetEndZ;
                    rsTargetStartX = startX;
                    rsTargetStartZ = startZ;
                    rsTargetEndX   = endX;
                    rsTargetEndZ   = endZ;
                }
                // Apply smoothing to render area
                if (rsCurrentPosition < 1f)
                {
                    startX             = rsOldStartX + (rsTargetStartX - rsOldStartX) * rsCurrentPosition;
                    startZ             = rsOldStartZ + (rsTargetStartZ - rsOldStartZ) * rsCurrentPosition;
                    endX               = rsOldEndX + (rsTargetEndX - rsOldEndX) * rsCurrentPosition;
                    endZ               = rsOldEndZ + (rsTargetEndZ - rsOldEndZ) * rsCurrentPosition;
                    rsCurrentPosition += 1f / (PRModSettings.smoothRenderAreaSteps + 1);
                }
            }

            float distX = endX - startX;
            float distZ = endZ - startZ;

            // Calculate basic values that are used for rendering
            int imageWidth;
            int imageHeight;

            if (PRModSettings.outputImageFixedHeight > 0)
            {
                imageHeight = PRModSettings.outputImageFixedHeight;
                imageWidth  = (int)((float)imageHeight / distZ * distX);
            }
            else
            {
                imageWidth  = (int)(distX * PRModSettings.pixelPerCell);
                imageHeight = (int)(distZ * PRModSettings.pixelPerCell);
            }

            int renderCountX = (int)Math.Ceiling((float)imageWidth / RenderTextureSize);
            int renderCountZ = (int)Math.Ceiling((float)imageHeight / RenderTextureSize);
            int renderWidth  = (int)Math.Ceiling((float)imageWidth / renderCountX);
            int renderHeight = (int)Math.Ceiling((float)imageHeight / renderCountZ);

            float cameraPosX       = (float)distX / 2 / renderCountX;
            float cameraPosZ       = (float)distZ / 2 / renderCountZ;
            float orthographicSize = Math.Min(cameraPosX, cameraPosZ);

            orthographicSize = cameraPosZ;
            Vector3 cameraBasePos = new Vector3(cameraPosX, 15f + (orthographicSize - 11f) / 49f * 50f, cameraPosZ);

            RenderTexture renderTexture = RenderTexture.GetTemporary(renderWidth, renderHeight, 24);

            imageTexture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGB24, false);

            Camera       camera    = Find.Camera;
            CameraDriver camDriver = camera.GetComponent <CameraDriver>();

            camDriver.enabled = false;

            // Store current camera data
            Vector3 rememberedRootPos      = map.rememberedCameraPos.rootPos;
            float   rememberedRootSize     = map.rememberedCameraPos.rootSize;
            float   rememberedFarClipPlane = camera.farClipPlane;

            // Overwrite current view rect in the camera driver
            CellRect camViewRect       = camDriver.CurrentViewRect;
            int      camRectMinX       = Math.Min((int)startX, camViewRect.minX);
            int      camRectMinZ       = Math.Min((int)startZ, camViewRect.minZ);
            int      camRectMaxX       = Math.Max((int)Math.Ceiling(endX), camViewRect.maxX);
            int      camRectMaxZ       = Math.Max((int)Math.Ceiling(endZ), camViewRect.maxZ);
            Traverse camDriverTraverse = Traverse.Create(camDriver);

            camDriverTraverse.Field("lastViewRect").SetValue(CellRect.FromLimits(camRectMinX, camRectMinZ, camRectMaxX, camRectMaxZ));
            camDriverTraverse.Field("lastViewRectGetFrame").SetValue(Time.frameCount);
            yield return(new WaitForEndOfFrame());

            // Set camera values needed for rendering
            camera.orthographicSize = orthographicSize;
            camera.farClipPlane     = cameraBasePos.y + 6.5f;

            // Create a temporary camera for rendering

            /*Camera tmpCam = Camera.Instantiate(camera);
             * tmpCam.orthographicSize = orthographicSize;
             * tmpCam.farClipPlane = cameraPos.y + 6.5f;*/

            // Set render textures
            //tmpCam.targetTexture = renderTexture;
            camera.targetTexture = renderTexture;
            RenderTexture.active = renderTexture;

            // Render the image texture
            if (PRModSettings.renderWeather)
            {
                map.weatherManager.DrawAllWeather();
            }
            for (int i = 0; i < renderCountZ; i++)
            {
                for (int j = 0; j < renderCountX; j++)
                {
                    camera.transform.position = new Vector3(startX + cameraBasePos.x * (2 * j + 1), cameraBasePos.y, startZ + cameraBasePos.z * (2 * i + 1));
                    camera.Render();
                    imageTexture.ReadPixels(new Rect(0, 0, renderWidth, renderHeight), renderWidth * j, renderHeight * i, false);
                }
            }

            // Restore camera and viewport
            RenderTexture.active = null;
            //tmpCam.targetTexture = null;
            camera.targetTexture = null;
            camera.farClipPlane  = rememberedFarClipPlane;
            camDriver.SetRootPosAndSize(rememberedRootPos, rememberedRootSize);
            camDriver.enabled = true;

            RenderTexture.ReleaseTemporary(renderTexture);

            // Switch back to world view if needed
            if (rememberedWorldRendered)
            {
                CameraJumper.TryShowWorld();
            }

            // Switch back to remembered map if needed
            if (switchedMap)
            {
                Current.Game.CurrentMap = rememberedMap;
            }

            // Sinal finished rendering
            renderingInt = false;
            yield return(null);

            // Start encoding
            DoEncoding();

            yield break;
        }
Esempio n. 43
0
 private void Start()
 {
     Cursor.visible = false;
     Cursor.lockState = CursorLockMode.Confined;
     cam = Camera.main;
 }
Esempio n. 44
0
 private void Start()
 {
     rb  = GetComponent <Rigidbody2D>();
     cam = Camera.main;
 }
Esempio n. 45
0
	private GameManager _GameManager; 	// GameObject responsible for the management of the game
	
	// Use this for initialization
	void Start () 
	{
		PlayerCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>(); // Find the Camera's GameObject from its tag 
		_GameManager = gameObject.GetComponent<GameManager>();
	}
Esempio n. 46
0
 // Start is called before the first frame update
 void Start()
 {
     controller = GetComponent<CharacterController>(); //on vient recuperer le composant CharacterController du Player
     mainCam = Camera.main;
 }
    public IEnumerator EndGame(bool win = false)
    {
        gameState = GameState.Ended;

        percentage.SetText(Mathf.RoundToInt((levelLength - targets.Count) / (float)levelLength * 100) + "%");

        loseScreen.SetActive(true);

        if (win)
        {
            loseText.SetText("You Win!");
            percentage.SetText("100%");
            progressBar.value = 1f;
        }

        //if(score > highScore) {
        //    highScore = score;
        //    PlayerPrefs.SetInt("HighScore", highScore);
        //    highScoreText.SetText("" + highScore);
        //}


        foreach (Target t in targets)
        {
            targetPool.Return(t.gameObject);
        }
        targets.Clear();


        foreach (GameObject obj in dominoes)
        {
            obj.GetComponent <Rigidbody>().isKinematic = false;
            hitCheck             = obj.AddComponent <HitCheck>();
            hitCheck.requiredTag = "Domino";

            if (obj.transform.localRotation == Quaternion.identity)
            {
                hitCheck.clip = fall1;
            }
            else
            {
                hitCheck.clip = fall2;
            }
        }



        Vector3 targetPos = path.transform.position + camOffset * 5f;
        Camera  camScript = cam.GetComponent <Camera>();

        while ((cam.position - targetPos).magnitude > 0.05f)
        {
            cam.position = Vector3.Lerp(cam.position, targetPos, 0.05f);
            camScript.orthographicSize = Mathf.Lerp(camScript.orthographicSize, camZoom, 0.05f);
            yield return(0);
        }
        dominoes[0].GetComponent <Rigidbody>().AddForce(dominoes[0].transform.forward * 100f);

        if (dominoes.Count > 2)
        {
            while (!hitCheck.isHit)
            {
                yield return(0);
            }
        }
        Destroy(hitCheck);
        yield return(new WaitForSeconds(2f));

        if (win)
        {
            yield return(new WaitForSeconds(image.Reveal() + 2f));

            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        }
        else
        {
            playAgain.SetActive(true);
        }
    }
Esempio n. 48
0
    Rigidbody2D rig;    //rigidbody holder

	void Start () {
        rig = GetComponent<Rigidbody2D>(); //assign holder to rigidbody on playable character
        cam = Camera.main;  //assign camera hold to main camera
	}
 public static float GetWidth(this Camera camera)
 {
     return(2f * camera.orthographicSize * camera.aspect);
 }
        static void InitializeCameraData(LightweightRenderPipelineAsset settings, Camera camera, LWRPAdditionalCameraData additionalCameraData, out CameraData cameraData)
        {
            const float kRenderScaleThreshold = 0.05f;

            cameraData.camera          = camera;
            cameraData.isStereoEnabled = IsStereoEnabled(camera);

            int msaaSamples = 1;

            if (camera.allowMSAA && settings.msaaSampleCount > 1)
            {
                msaaSamples = (camera.targetTexture != null) ? camera.targetTexture.antiAliasing : settings.msaaSampleCount;
            }

            if (Camera.main == camera && camera.cameraType == CameraType.Game && camera.targetTexture == null)
            {
                bool msaaSampleCountHasChanged         = false;
                int  currentQualitySettingsSampleCount = QualitySettings.antiAliasing;
                if (currentQualitySettingsSampleCount != msaaSamples &&
                    !(currentQualitySettingsSampleCount == 0 && msaaSamples == 1))
                {
                    msaaSampleCountHasChanged = true;
                }

                // There's no exposed API to control how a backbuffer is created with MSAA
                // By settings antiAliasing we match what the amount of samples in camera data with backbuffer
                // We only do this for the main camera and this only takes effect in the beginning of next frame.
                // This settings should not be changed on a frame basis so that's fine.
                QualitySettings.antiAliasing = msaaSamples;

                if (cameraData.isStereoEnabled && msaaSampleCountHasChanged)
                {
                    XR.XRDevice.UpdateEyeTextureMSAASetting();
                }
            }

            cameraData.isSceneViewCamera  = camera.cameraType == CameraType.SceneView;
            cameraData.isHdrEnabled       = camera.allowHDR && settings.supportsHDR;
            cameraData.postProcessLayer   = camera.GetComponent <PostProcessLayer>();
            cameraData.postProcessEnabled = cameraData.postProcessLayer != null && cameraData.postProcessLayer.isActiveAndEnabled;

            // Disables postprocessing in mobile VR. It's stable on mobile yet.
            if (cameraData.isStereoEnabled && Application.isMobilePlatform)
            {
                cameraData.postProcessEnabled = false;
            }

            Rect cameraRect = camera.rect;

            cameraData.isDefaultViewport = (!(Math.Abs(cameraRect.x) > 0.0f || Math.Abs(cameraRect.y) > 0.0f ||
                                              Math.Abs(cameraRect.width) < 1.0f || Math.Abs(cameraRect.height) < 1.0f));

            // If XR is enabled, use XR renderScale.
            // Discard variations lesser than kRenderScaleThreshold.
            // Scale is only enabled for gameview.
            float usedRenderScale = XRGraphics.enabled ? XRGraphics.eyeTextureResolutionScale : settings.renderScale;

            cameraData.renderScale = (Mathf.Abs(1.0f - usedRenderScale) < kRenderScaleThreshold) ? 1.0f : usedRenderScale;
            cameraData.renderScale = (camera.cameraType == CameraType.Game) ? cameraData.renderScale : 1.0f;

            bool anyShadowsEnabled = settings.supportsMainLightShadows || settings.supportsAdditionalLightShadows;

            cameraData.maxShadowDistance = (anyShadowsEnabled) ? settings.shadowDistance : 0.0f;

            if (additionalCameraData != null)
            {
                cameraData.maxShadowDistance     = (additionalCameraData.renderShadows) ? cameraData.maxShadowDistance : 0.0f;
                cameraData.requiresDepthTexture  = additionalCameraData.requiresDepthTexture;
                cameraData.requiresOpaqueTexture = additionalCameraData.requiresColorTexture;
            }
            else
            {
                cameraData.requiresDepthTexture  = settings.supportsCameraDepthTexture;
                cameraData.requiresOpaqueTexture = settings.supportsCameraOpaqueTexture;
            }

            cameraData.requiresDepthTexture |= cameraData.isSceneViewCamera || cameraData.postProcessEnabled;

            var  commonOpaqueFlags        = SortingCriteria.CommonOpaque;
            var  noFrontToBackOpaqueFlags = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges | SortingCriteria.CanvasOrder;
            bool hasHSRGPU = SystemInfo.hasHiddenSurfaceRemovalOnGPU;
            bool canSkipFrontToBackSorting = (camera.opaqueSortMode == OpaqueSortMode.Default && hasHSRGPU) || camera.opaqueSortMode == OpaqueSortMode.NoDistanceSort;

            cameraData.defaultOpaqueSortFlags = canSkipFrontToBackSorting ? noFrontToBackOpaqueFlags : commonOpaqueFlags;
            cameraData.captureActions         = CameraCaptureBridge.GetCaptureActions(camera);

            cameraData.cameraTargetDescriptor = CreateRenderTextureDescriptor(camera, cameraData.renderScale,
                                                                              cameraData.isStereoEnabled, cameraData.isHdrEnabled, msaaSamples);
        }
 public static Vector3 GetWorldCenter(this Camera camera)
 {
     return(camera.ScreenToWorldPoint(camera.GetScreenCenter()));
 }
 public static Vector3 GetWorldBorderPoint(this Camera camera, DiagonalDirection direction)
 {
     return(camera.GetScreenBorderPoint(direction));
 }
Esempio n. 53
0
 public void ManageDirection(GameTime gameTime, MouseState mouse, Rectangle playerPosition, Camera camera)
 {
     if (movement != Vector2.Zero)
     {
         Move(movement, gameTime); return;
     }
     movement = new Vector2(mouse.X - playerPosition.X + camera.Border, mouse.Y - playerPosition.Y);
     if (movement != Vector2.Zero)
     {
         movement.Normalize();
     }
     Move(movement, gameTime);
 }
 public static Vector3 GetScreenCenter(this Camera camera)
 {
     return(new Vector3(Screen.width / 2, Screen.height / 2, camera.nearClipPlane));
 }
Esempio n. 55
0
 void Start()
 {
     camera.clearFlags = CameraClearFlags.Depth;
     cameraTransform   = camera.transform;
     skyCam            = GetComponent <Camera>();
 }
 public static float GetHeight(this Camera camera)
 {
     return(camera.orthographicSize * 2f);
 }
Esempio n. 57
0
    // On-demand create any objects we need for water
    private void CreateWaterObjects(Camera currentCamera, out Camera reflectionCamera, out Camera refractionCamera)
    {
        WaterMode mode = GetWaterMode();

        reflectionCamera = null;
        refractionCamera = null;

        if (mode >= WaterMode.Reflective)
        {
            // Reflection render texture
            if (!m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize)
            {
                if (m_ReflectionTexture)
                {
                    DestroyImmediate(m_ReflectionTexture);
                }
                m_ReflectionTexture              = new RenderTexture(m_TextureSize, m_TextureSize, 16);
                m_ReflectionTexture.name         = "__WaterReflection" + GetInstanceID();
                m_ReflectionTexture.isPowerOfTwo = true;
                m_ReflectionTexture.hideFlags    = HideFlags.DontSave;
                m_OldReflectionTextureSize       = m_TextureSize;
            }

            // Camera for reflection
            m_ReflectionCameras.TryGetValue(currentCamera, out reflectionCamera);
            if (!reflectionCamera)               // catch both not-in-dictionary and in-dictionary-but-deleted-GO
            {
                GameObject go = new GameObject("Water Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
                reflectionCamera                    = go.GetComponent <Camera>();
                reflectionCamera.enabled            = false;
                reflectionCamera.transform.position = transform.position;
                reflectionCamera.transform.rotation = transform.rotation;
                reflectionCamera.gameObject.AddComponent <FlareLayer>();
                go.hideFlags = HideFlags.HideAndDontSave;
                m_ReflectionCameras [currentCamera] = reflectionCamera;
            }
        }

        if (mode >= WaterMode.Refractive)
        {
            // Refraction render texture
            if (!m_RefractionTexture || m_OldRefractionTextureSize != m_TextureSize)
            {
                if (m_RefractionTexture)
                {
                    DestroyImmediate(m_RefractionTexture);
                }
                m_RefractionTexture              = new RenderTexture(m_TextureSize, m_TextureSize, 16);
                m_RefractionTexture.name         = "__WaterRefraction" + GetInstanceID();
                m_RefractionTexture.isPowerOfTwo = true;
                m_RefractionTexture.hideFlags    = HideFlags.DontSave;
                m_OldRefractionTextureSize       = m_TextureSize;
            }

            // Camera for refraction
            m_RefractionCameras.TryGetValue(currentCamera, out refractionCamera);
            if (!refractionCamera)               // catch both not-in-dictionary and in-dictionary-but-deleted-GO
            {
                GameObject go = new GameObject("Water Refr Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
                refractionCamera                    = go.GetComponent <Camera>();
                refractionCamera.enabled            = false;
                refractionCamera.transform.position = transform.position;
                refractionCamera.transform.rotation = transform.rotation;
                refractionCamera.gameObject.AddComponent <FlareLayer>();
                go.hideFlags = HideFlags.HideAndDontSave;
                m_RefractionCameras [currentCamera] = refractionCamera;
            }
        }
    }
Esempio n. 58
0
 // Start is called before the first frame update
 void Start()
 {
     cam = this.GetComponentInChildren <Camera>();
     cam.transform.LookAt(this.transform.position);
 }
Esempio n. 59
0
 public MapComponent(Func <PartMapComponent> partMapProvider, Camera cam, GraphicConfiguration graphic)
 {
     this.graphic         = graphic;
     this.cam             = cam;
     this.partMapProvider = partMapProvider;
 }
Esempio n. 60
0
    // This is called when it's known that the object will be rendered by some
    // camera. We render reflections / refractions and do other updates here.
    // Because the script executes in edit mode, reflections for the scene view
    // camera will just work!
    public void OnWillRenderObject()
    {
        if (!enabled || !GetComponent <Renderer>() || !GetComponent <Renderer>().sharedMaterial || !GetComponent <Renderer>().enabled)
        {
            return;
        }

        Camera cam = Camera.current;

        if (!cam)
        {
            return;
        }

        // Safeguard from recursive water reflections.
        if (s_InsideWater)
        {
            return;
        }
        s_InsideWater = true;

        // Actual water rendering mode depends on both the current setting AND
        // the hardware support. There's no point in rendering refraction textures
        // if they won't be visible in the end.
        m_HardwareWaterSupport = FindHardwareWaterSupport();
        WaterMode mode = GetWaterMode();

        Camera reflectionCamera, refractionCamera;

        CreateWaterObjects(cam, out reflectionCamera, out refractionCamera);

        // find out the reflection plane: position and normal in world space
        Vector3 pos    = transform.position;
        Vector3 normal = transform.up;

        // Optionally disable pixel lights for reflection/refraction
        int oldPixelLightCount = QualitySettings.pixelLightCount;

        if (m_DisablePixelLights)
        {
            QualitySettings.pixelLightCount = 0;
        }

        UpdateCameraModes(cam, reflectionCamera);
        UpdateCameraModes(cam, refractionCamera);

        // Render reflection if needed
        if (mode >= WaterMode.Reflective)
        {
            // Reflect camera around reflection plane
            float   d = -Vector3.Dot(normal, pos) - m_ClipPlaneOffset;
            Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);

            Matrix4x4 reflection = Matrix4x4.zero;
            CalculateReflectionMatrix(ref reflection, reflectionPlane);
            Vector3 oldpos = cam.transform.position;
            Vector3 newpos = reflection.MultiplyPoint(oldpos);
            reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;

            // Setup oblique projection matrix so that near plane is our reflection
            // plane. This way we clip everything below/above it for free.
            Vector4 clipPlane = CameraSpacePlane(reflectionCamera, pos, normal, 1.0f);
            reflectionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane);

            reflectionCamera.cullingMask   = ~(1 << 4) & m_ReflectLayers.value;           // never render water layer
            reflectionCamera.targetTexture = m_ReflectionTexture;
            GL.SetRevertBackfacing(true);
            reflectionCamera.transform.position = newpos;
            Vector3 euler = cam.transform.eulerAngles;
            reflectionCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
            reflectionCamera.Render();
            reflectionCamera.transform.position = oldpos;
            GL.SetRevertBackfacing(false);
            GetComponent <Renderer>().sharedMaterials [0].SetTexture("_ReflectionTex", m_ReflectionTexture);
            if (GetComponent <Renderer>().sharedMaterials.Length > 1)
            {
                GetComponent <Renderer>().sharedMaterials [1].SetTexture("_ReflectionTex", m_ReflectionTexture);
            }
        }

        // Render refraction
        if (mode >= WaterMode.Refractive)
        {
            refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix;

            // Setup oblique projection matrix so that near plane is our reflection
            // plane. This way we clip everything below/above it for free.
            Vector4 clipPlane = CameraSpacePlane(refractionCamera, pos, normal, -1.0f);
            refractionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane);

            refractionCamera.cullingMask        = ~(1 << 4) & m_RefractLayers.value;      // never render water layer
            refractionCamera.targetTexture      = m_RefractionTexture;
            refractionCamera.transform.position = cam.transform.position;
            refractionCamera.transform.rotation = cam.transform.rotation;
            refractionCamera.Render();
            GetComponent <Renderer>().sharedMaterials [0].SetTexture("_RefractionTex", m_RefractionTexture);
            if (GetComponent <Renderer>().sharedMaterials.Length > 1)
            {
                GetComponent <Renderer>().sharedMaterials [1].SetTexture("_RefractionTex", m_RefractionTexture);
            }
        }

        // Restore pixel light count
        if (m_DisablePixelLights)
        {
            QualitySettings.pixelLightCount = oldPixelLightCount;
        }

        // Setup shader keywords based on water mode
        switch (mode)
        {
        case WaterMode.Simple:
            Shader.EnableKeyword("WATER_SIMPLE");
            Shader.DisableKeyword("WATER_CUBE");
            Shader.DisableKeyword("WATER_REFLECTIVE");
            Shader.DisableKeyword("WATER_REFRACTIVE");
            break;

        case WaterMode.Cube:
            Shader.DisableKeyword("WATER_SIMPLE");
            Shader.EnableKeyword("WATER_CUBE");
            Shader.DisableKeyword("WATER_REFLECTIVE");
            Shader.DisableKeyword("WATER_REFRACTIVE");
            break;

        case WaterMode.Reflective:
            Shader.DisableKeyword("WATER_SIMPLE");
            Shader.DisableKeyword("WATER_CUBE");
            Shader.EnableKeyword("WATER_REFLECTIVE");
            Shader.DisableKeyword("WATER_REFRACTIVE");
            break;

        case WaterMode.Refractive:
            Shader.DisableKeyword("WATER_SIMPLE");
            Shader.DisableKeyword("WATER_CUBE");
            Shader.DisableKeyword("WATER_REFLECTIVE");
            Shader.EnableKeyword("WATER_REFRACTIVE");
            break;
        }

        s_InsideWater = false;
    }