コード例 #1
0
    void Reflect(Collider2D _collider)
    {
        m_IsReflected = true;

        var _direction = transform.TransformDirection(Vector3.right);

        // hard
        // todo: rough solution.
        var _rayResults = Physics2D.RaycastAll(
            transform.TransformPoint(0.5f * Vector3.left),
            _direction,
            1f,
            reflectionMask);

        foreach (var _rayResult in _rayResults)
        {
            if (_rayResult.collider != _collider)
            {
                continue;
            }

            _direction = Vector3.Reflect(_direction, _rayResult.normal);
            var _angle = transform.eulerAngles;
            _angle.z = TransformHelper.VectorToDeg(_direction);
            transform.eulerAngles = _angle;

            var _velocity = transform.rigidbody2D.velocity;
            transform.rigidbody2D.velocity = Vector3.Reflect(_velocity, _rayResult.normal);

            return;
        }

        Debug.Log("RayCast failed!");
    }
コード例 #2
0
    //// Updates the transform based on the behavior.
    //// Returns true if the state of the transform changed.
    //// This ignores interpolation.
    //public override bool tryMove(Transform transform, float deltaTime)
    //{
    //       transform.position = getTargetPosition(transform);
    //	return true;
    //}

    // Calculate the direction of the movement behavior after processing user inputs.
    private Vector3 calculateTargetPosition(Transform transform)
    {
        float horizontalStep = m_inputMagnitude.x > 0 ? m_data.forwardStepSize.x : m_data.reverseStepSize.x;
        float verticalStep   = m_inputMagnitude.y > 0 ? m_data.forwardStepSize.y : m_data.reverseStepSize.y;
        float depthStep      = m_inputMagnitude.z > 0 ? m_data.forwardStepSize.z : m_data.reverseStepSize.z;

        Vector3 finalDirection = Vector3.zero;

        if (getMoveRelative())
        {
            // Let x = right, z = forward, y = up. TODO: Perhaps get these axis from the TransformHelper.
            finalDirection += transform.right * horizontalStep * m_inputMagnitude.x;
            finalDirection += transform.up * verticalStep * m_inputMagnitude.y;
            finalDirection += transform.forward * depthStep * m_inputMagnitude.z;
        }
        else
        {
            TransformHelper.setAxisValue(
                ref finalDirection,
                TransformHelper.HorizontalAxis,
                horizontalStep * m_inputMagnitude.x
                );
            TransformHelper.setAxisValue(
                ref finalDirection,
                TransformHelper.VerticalAxis,
                verticalStep * m_inputMagnitude.y
                );
            TransformHelper.setAxisValue(
                ref finalDirection,
                TransformHelper.DepthAxis,
                depthStep * m_inputMagnitude.z
                );
        }
        return(finalDirection);
    }
コード例 #3
0
 /// <summary>
 /// 使用指定技能
 /// </summary>
 /// <param name="skillid">技能编号</param>
 /// <param name="isBatter">是否连击</param>
 public void AttackUseSkill(int skillid, bool isBatter)
 {
     //如果是连击,找当前技能的下一个连击技能
     if (currentUseSkill != null && isBatter)
     {
         skillid = currentUseSkill.nextBatterId;
     }
     //准备技能
     currentUseSkill = chSkillMgr.PrepareSkill(skillid);
     if (currentUseSkill != null)
     {
         //目标选择
         var selectedTaget = SelectTarget();
         if (selectedTaget != null)
         {
             //目标选中指示的显隐
             if (currentSelectedTarget != null)
             {
                 TransformHelper.FindChild(currentSelectedTarget, "selected").GetComponent <Renderer>().enabled = false;
             }
             currentSelectedTarget = selectedTaget.transform;
             TransformHelper.FindChild(currentSelectedTarget, "selected").GetComponent <Renderer>().enabled = true;
             //转向目标
             transform.LookAt(currentSelectedTarget);
         }
         //攻击动画
         chAnim.PlayAnimation(currentUseSkill.animtionName);
     }
 }
コード例 #4
0
        public string DecryptRun(string message, string password)
        {
            //Requires int
            int shiftBy = TransformHelper.PasswordStrToKeyInt(password);

            byte[] bytesToShift = Encoding.Unicode.GetBytes(message);

            int byteCount = bytesToShift.Length;
            var shifted   = new byte[byteCount];

            for (int x = 0; x < byteCount; x++)
            {
                var b = bytesToShift[x];

                byte temp;

                if (x % 2 == 0)
                {
                    temp = (byte)(b - shiftBy);
                }
                else
                {
                    temp = (byte)(b + shiftBy);
                }

                shifted[x] = temp;
            }

            var shiftedString = Encoding.Unicode.GetString(shifted);

            return(shiftedString);
        }
コード例 #5
0
        public byte[] DecryptCbc(byte[] ciphertext, byte[] seed)
        {
            using (var rand = new DeterministicCryptoRandomGenerator(seed, false))
            {
                byte[] iv;
                using (var aesAlg = Aes.Create())
                {
                    aesAlg.KeySize = AesKeySize;
                    var keyBytes = new byte[aesAlg.KeySize / 8];
                    rand.GetBytes(keyBytes, 0, aesAlg.KeySize / 8);

                    iv = keyBytes;

                    aesAlg.Key = keyBytes;

                    aesAlg.IV      = iv;
                    aesAlg.Mode    = CipherMode.CBC;
                    aesAlg.Padding = PaddingMode.Zeros;

                    // Create the streams used for encryption.
                    // Open a new memory stream to write the encrypted data to
                    // Create a crypto stream to perform encryption
                    using (var decryptor = aesAlg.CreateDecryptor())
                    {
                        // write encrypted bytes to memory
                        return(TransformHelper.PerformCryptography(decryptor, ciphertext));
                    }
                }
            }
        }
コード例 #6
0
        public byte[] ConputeMacWithKey(byte[] data, byte[] seed)
        {
            using (var rand = new DeterministicCryptoRandomGenerator(seed, false))
            {
                byte[] iv;
                byte[] ciphertext;
                byte[] keyBytes;
                using (var aesAlg = Aes.Create())
                {
                    aesAlg.KeySize = AesKeySize;
                    keyBytes       = new byte[aesAlg.KeySize / 8];
                    rand.GetBytes(keyBytes, 0, aesAlg.KeySize / 8);

                    iv = new byte[AesKeySize / 8];

                    aesAlg.Key     = keyBytes;
                    aesAlg.Padding = PaddingMode.PKCS7;

                    aesAlg.IV   = iv;
                    aesAlg.Mode = CipherMode.CBC;

                    // Create the streams used for encryption.
                    // Open a new memory stream to write the encrypted data to
                    // Create a crypto stream to perform encryption
                    using (var ecryptor = aesAlg.CreateEncryptor())
                    {
                        // write encrypted bytes to memory
                        ciphertext = TransformHelper.PerformCryptography(ecryptor, data);
                    }
                }

                // return last block
                return(ciphertext.Skip(ciphertext.Length - AesBlockSize).ToArray());
            }
        }
コード例 #7
0
    void CreateGunPrefab(GunHandler handler)
    {
        GameObject gun = GameObject.Instantiate(handler.gun.prefabObj);

        gun.transform.SetParent(handler.transform);
        TransformHelper.SetLocalTransformData(gun.transform, handler.gun.prefabLocalData);
    }
コード例 #8
0
        public HttpResponseMessage DeleteCustomer(string CustomerOperateDTO)
        {
            CustomerOperateDTO dto          = TransformHelper.ConvertBase64JsonStringToDTO <CustomerOperateDTO>(CustomerOperateDTO);
            ResultDTO <object> actionresult = new ResultDTO <object>();

            try
            {
                actionresult.SubmitResult = _ICustomerServices.DeleteCustomer(dto);
            }
            catch (DbUpdateException ex)
            {
                actionresult.SubmitResult = false;
                actionresult.Message      = "此条信息已使用不可删除!";
            }
            catch (Exception ex)
            {
                actionresult.SubmitResult = false;
                actionresult.Message      = ex.Message;
            }

            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(JsonConvert.SerializeObject(actionresult),
                                            System.Text.Encoding.GetEncoding("UTF-8"),
                                            "application/json")
            };

            return(result);
        }
コード例 #9
0
        public HttpResponseMessage GetCustomerList(string CustomerSearchDTO)
        {
            CustomerSearchDTO dto = TransformHelper.ConvertBase64JsonStringToDTO <CustomerSearchDTO>(CustomerSearchDTO);

            ResultDTO <List <CustomerResultDTO> > actionresult = new ResultDTO <List <CustomerResultDTO> >();

            try
            {
                if (dto.QueryType == 0)//查询客户信息
                {
                    actionresult.Object = _ICustomerServices.GetCustomerList(dto);
                }
                else if (dto.QueryType == 1)//查询相似客户
                {
                    actionresult.Object = _ICustomerServices.GetSimilarCustomerList(dto);
                }
                actionresult.SubmitResult = true;
                actionresult.rows         = dto.rows;
                actionresult.page         = dto.page;
                actionresult.Count        = dto.Count;
            }
            catch (Exception ex)
            {
                actionresult.SubmitResult = false;
                actionresult.Message      = ex.Message;
            }
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(JsonConvert.SerializeObject(actionresult),
                                            System.Text.Encoding.GetEncoding("UTF-8"),
                                            "application/json")
            };

            return(result);
        }
コード例 #10
0
    public GameObject AddPrf(GameObject _prf, Anchor9 _anchor)
    {
        var _go = (GameObject)Instantiate(_prf);

        TransformHelper.SetParentWithoutScale(_go, anchors[(int)_anchor].gameObject);
        return(_go);
    }
コード例 #11
0
        public void TestMethod1()
        {
            //关账日
            //新增
            testcontroller.GetAccountDateList();
            AccountDateOperateDTO adddto = new AccountDateOperateDTO();

            adddto.AccountDateBelongModel = "基础数据";
            adddto.AccountDateName        = "单元测试关账日名称";
            var addresult   = JsonConvert.DeserializeObject <ResultDTO <object> >(testcontroller.AddAccountDate(adddto).Content.ReadAsStringAsync().Result);
            var resultlist1 = JsonConvert.DeserializeObject <List <AccountDateResultDTO> >(testcontroller.GetAccountDateList().Content.ReadAsStringAsync().Result);
            var target      = resultlist1.Where(m => m.AccountDateName == "单元测试关账日名称").FirstOrDefault();

            Assert.IsNotNull(target);

            //修改
            adddto.AccountDateID   = target.AccountDateID;
            adddto.AccountDateName = "修改单元测试关账日名称";
            var updateresult = JsonConvert.DeserializeObject <ResultDTO <object> >(testcontroller.UpdateAccountDate(adddto).Content.ReadAsStringAsync().Result);
            var resultlist2  = JsonConvert.DeserializeObject <List <AccountDateResultDTO> >(testcontroller.GetAccountDateList().Content.ReadAsStringAsync().Result);

            target = resultlist2.Where(m => m.AccountDateName == "修改单元测试关账日名称").FirstOrDefault();
            Assert.IsNotNull(target);

            //删除
            AccountDateSearchDTO deletedto = new AccountDateSearchDTO();

            deletedto.AccountDateID = target.AccountDateID;
            var deletedtostr = TransformHelper.ConvertDTOTOBase64JsonString(deletedto);
            var deleteresult = JsonConvert.DeserializeObject <ResultDTO <object> >(testcontroller.DeleteAccountDate(deletedtostr).Content.ReadAsStringAsync().Result);
            var resultlist3  = JsonConvert.DeserializeObject <List <AccountDateResultDTO> >(testcontroller.GetAccountDateList().Content.ReadAsStringAsync().Result);

            target = resultlist3.Where(m => m.AccountDateID == target.AccountDateID).FirstOrDefault();
            Assert.IsNull(target);
        }
コード例 #12
0
 // Update is called once per frame
 void Update()
 {
     if (_world_anchor != null && tfFrameName != null)
     {
         // If one works, both should;
         // odom represents world zero/ _world_anchor
         TfVector3?   tfVec  = _listener.LookupTranslation("odom", tfFrameName);
         TfQuaternion?tfQuat = _listener.LookupRotation("odom", tfFrameName);
         if (tfVec.HasValue && tfQuat.HasValue)
         {
             Vector3    translationU = TransformHelper.VectorTfToUnity(tfVec.Value);
             Quaternion quatU        = new Quaternion((float)tfQuat.Value.x, (float)tfQuat.Value.y, (float)tfQuat.Value.y, (float)tfQuat.Value.w);
             DestroyImmediate(_self_anchor);
             transform.SetPositionAndRotation(_world_anchor.transform.position + translationU, quatU);
             _self_anchor = gameObject.AddComponent <WorldAnchor>();
         }
         else
         {
             Debug.LogWarning("Collocation for " + this.gameObject + " failed because TransformListener.LookupTranslation failed to find translation odom->" + tfFrameName);
         }
     }
     else if (DEBUG_NOISY)
     {
         Debug.LogWarning("Collocation for " + this.gameObject + " failed because there is no anchor or no frame name was specified.");
     }
 }
コード例 #13
0
        public HttpResponseMessage DeleteUser(string UserOperate)
        {
            ResultDTO <UserResultDTO> resultdto = new ResultDTO <UserResultDTO>();

            try
            {
                UserOperate dto = TransformHelper.ConvertBase64JsonStringToDTO <UserOperate>(UserOperate);
                resultdto.SubmitResult = _lUserAuthorityServices.DeleteUser(dto);
            }
            catch (DbUpdateException)
            {
                resultdto.SubmitResult = false;
                resultdto.Message      = "此条信息已使用不可删除!";
            }
            catch (Exception ex)
            {
                resultdto.SubmitResult = false;
                resultdto.Message      = ex.Message;
            }

            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(JsonConvert.SerializeObject(resultdto),
                                            System.Text.Encoding.GetEncoding("UTF-8"),
                                            "application/json")
            };

            return(result);
        }
コード例 #14
0
ファイル: UnitTest15.cs プロジェクト: war-man/TCDMS
        public void TestMethod1()
        {
            //仪器类型
            //新增
            testcontroller.GetInstrumentTypeList();
            InstrumentTypeOperateDTO adddto = new InstrumentTypeOperateDTO();

            adddto.InstrumentTypeName = "单元测试钢材";
            adddto.CreateTime         = DateTime.Now;
            var addresult   = JsonConvert.DeserializeObject <ResultDTO <object> >(testcontroller.AddInstrumentType(adddto).Content.ReadAsStringAsync().Result);
            var resultlist1 = JsonConvert.DeserializeObject <List <InstrumentTypeResultDTO> >(testcontroller.GetInstrumentTypeList().Content.ReadAsStringAsync().Result);
            var target      = resultlist1.Where(m => m.InstrumentTypeName == "单元测试钢材").FirstOrDefault();

            Assert.IsNotNull(target);

            //修改
            adddto.InstrumentTypeID   = target.InstrumentTypeID;
            adddto.InstrumentTypeName = "修改单元测试仪器类型名称";
            var updateresult = JsonConvert.DeserializeObject <ResultDTO <object> >(testcontroller.UpdateInstrumentType(adddto).Content.ReadAsStringAsync().Result);
            var resultlist2  = JsonConvert.DeserializeObject <List <InstrumentTypeResultDTO> >(testcontroller.GetInstrumentTypeList().Content.ReadAsStringAsync().Result);

            target = resultlist2.Where(m => m.InstrumentTypeName == "修改单元测试仪器类型名称").FirstOrDefault();
            Assert.IsNotNull(target);

            //删除
            InstrumentTypeSearchDTO deletedto = new InstrumentTypeSearchDTO();

            deletedto.InstrumentTypeID = target.InstrumentTypeID;
            var deletedtostr = TransformHelper.ConvertDTOTOBase64JsonString(deletedto);
            var deleteresult = JsonConvert.DeserializeObject <ResultDTO <object> >(testcontroller.DeleteProductType(deletedtostr).Content.ReadAsStringAsync().Result);
            var resultlist3  = JsonConvert.DeserializeObject <List <InstrumentTypeResultDTO> >(testcontroller.GetInstrumentTypeList().Content.ReadAsStringAsync().Result);

            target = resultlist3.Where(m => m.InstrumentTypeID == target.InstrumentTypeID).FirstOrDefault();
            Assert.IsNull(target);
        }
コード例 #15
0
        public NoteEditViewModel(INavigationService navigationService,
                                 IPermissionService permissionService,
                                 IFileSystem fileService,
                                 IMediaService mediaService,
                                 IVideoService videoService,
                                 ICommandResolver commandResolver,
                                 MediaHelper mediaHelper,
                                 TransformHelper transformHelper)
            : base(navigationService)
        {
            _permissionService = permissionService;
            _fileService       = fileService;
            _mediaService      = mediaService;
            _videoService      = videoService;
            _commandResolver   = commandResolver;

            _mediaHelper     = mediaHelper;
            _transformHelper = transformHelper;

            AttachButtonImageSource = ConstantsHelper.AttachmentLightIcon;
            CameraButtonImageSource = ConstantsHelper.CameraIcon;
            VideoButtonImageSource  = ConstantsHelper.VideoIcon;

            GalleryItemModels = new RangeObservableCollection <GalleryItemModel>();

            DescriptionTextChanged   = commandResolver.Command <string>(DescriptionChanged);
            TakePhotoCommand         = commandResolver.AsyncCommand(TakePhoto);
            TakeVideoCommand         = commandResolver.AsyncCommand(TakeVideo);
            PickMultipleMediaCommand = commandResolver.AsyncCommand(PickMultipleMedia);
            SaveNoteCommand          = commandResolver.AsyncCommand <string>(SaveNote);
            DeleteNoteCommand        = commandResolver.AsyncCommand(DeleteNote);
            SelectImageCommand       = commandResolver.AsyncCommand <GalleryItemModel>(SelectImage);
        }
コード例 #16
0
        public static Entity NewBlock(Vector3 positionValues, Texture2D texture, string typeName)
        {
            Entity block = EntityFactory.NewEntity(typeName);

            TransformComponent transformComponent = new TransformComponent(block, new Vector3(x: positionValues.X, y: positionValues.Y, z: positionValues.Z));
            ModelComponent     modelComponent     = new ModelComponent(block, AssetManager.Instance.GetContent <Model>("Models/block2"));

            modelComponent.World = Matrix.CreateWorld(transformComponent.Position, Vector3.Forward, Vector3.Up);
            TextureComponent   textureComponent   = new TextureComponent(block, texture);
            CollisionComponent collisionComponent = new CollisionComponent(block, new BoxVolume(EntityFactory.CreateBoundingBox(modelComponent.Model)));

            LightComponent  lightComponent  = new LightComponent(block, new Vector3(0, 7, -5), Color.White.ToVector4(), 10f, Color.Blue.ToVector4(), 0.2f, Color.White.ToVector4(), 1000f);
            EffectComponent effectComponent = new EffectComponent(block, AssetManager.Instance.GetContent <Effect>("Shading"));

            BlockComponent blockComponent = new BlockComponent(block);

            ComponentManager.Instance.AddComponentToEntity(block, transformComponent);
            ComponentManager.Instance.AddComponentToEntity(block, modelComponent);
            ComponentManager.Instance.AddComponentToEntity(block, textureComponent);
            ComponentManager.Instance.AddComponentToEntity(block, collisionComponent, typeof(CollisionComponent));
            ComponentManager.Instance.AddComponentToEntity(block, blockComponent);
            ComponentManager.Instance.AddComponentToEntity(block, effectComponent);
            ComponentManager.Instance.AddComponentToEntity(block, lightComponent);

            TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            TransformHelper.SetBoundingBoxPos(collisionComponent, transformComponent);
            //EntityFactory.AddBoundingBoxChildren((BoxVolume)collisionComponent);

            return(block);
        }
コード例 #17
0
        public byte[] EncryptEcb(byte[] data, byte[] seed, bool useEntropy = true)
        {
            byte[] ciphertext;
            using (var rand = new DeterministicCryptoRandomGenerator(seed, useEntropy))
            {
                using (var aesAlg = Aes.Create())
                {
                    var keyBytes = new byte[aesAlg.KeySize / 8];
                    rand.GetBytes(keyBytes, 0, aesAlg.KeySize / 8);
                    aesAlg.Key = keyBytes;

                    aesAlg.Mode    = CipherMode.ECB;
                    aesAlg.Padding = PaddingMode.Zeros;

                    // Create a crypto stream to perform encryption
                    using (ICryptoTransform ecryptor = aesAlg.CreateEncryptor())
                    {
                        // write encrypted bytes to memory
                        ciphertext = TransformHelper.PerformCryptography(ecryptor, data);
                    }
                }
            }

            return(ciphertext);
        }
コード例 #18
0
        public static Entity NewBasePlayer(String model, int gamePadIndex, Vector3 transformPos, Texture2D texture, String typeName)
        {
            Entity             player             = EntityFactory.NewEntity(typeName);
            TransformComponent transformComponent = new TransformComponent(player, transformPos);
            ModelComponent     modelComponent     = new ModelComponent(player, AssetManager.Instance.GetContent <Model>(model));
            VelocityComponent  velocityComponent  = new VelocityComponent(player);
            CollisionComponent collisionComponent = new CollisionComponent(player, new BoxVolume(EntityFactory.CreateBoundingBox(modelComponent.Model)));
            PlayerComponent    playerComponent    = new PlayerComponent(player);
            FrictionComponent  frictionComponent  = new FrictionComponent(player);
            TextureComponent   textureComponent   = new TextureComponent(player, texture);
            GravityComponent   gravityComponent   = new GravityComponent(player);
            EffectComponent    effectComponent    = new EffectComponent(player, AssetManager.Instance.GetContent <Effect>("Shading"));

            ComponentManager.Instance.AddComponentToEntity(player, modelComponent);
            ComponentManager.Instance.AddComponentToEntity(player, transformComponent);
            ComponentManager.Instance.AddComponentToEntity(player, velocityComponent);
            ComponentManager.Instance.AddComponentToEntity(player, collisionComponent, typeof(CollisionComponent));
            ComponentManager.Instance.AddComponentToEntity(player, playerComponent);
            ComponentManager.Instance.AddComponentToEntity(player, frictionComponent);
            ComponentManager.Instance.AddComponentToEntity(player, textureComponent);
            ComponentManager.Instance.AddComponentToEntity(player, gravityComponent);
            ComponentManager.Instance.AddComponentToEntity(player, effectComponent);

            TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            TransformHelper.SetBoundingBoxPos(collisionComponent, transformComponent);

            //TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            //TransformHelper.SetInitialBoundingSpherePos(collisionComponent, transformComponent);

            return(player);
        }
コード例 #19
0
ファイル: UseRender.cs プロジェクト: w1146869587/SharpSVG
        public static async Task Render(IElement element, IFrameContext context, RendererDirect2D render)
        {
            var href = element.GetHref();

            if (href == null)
            {
                return;
            }
            var fragment = (href.Scheme == "internal")
        ? element.OwnerDocument?.GetElementById(href.Fragment.Substring(1))
        : await LoadExternal(href, render, element.OwnerDocument.BaseUri);

            if (fragment == null)
            {
                return;
            }

            try
            {
                fragment.SetParentOverride(element);
                using (TransformHelper.CreatePosition(render, element, context))
                    await render.GetRenderer(fragment.ElementType)(
                        fragment,
                        context.Create(element.GetSize(context, context.Size)),
                        render
                        );
            }
            finally
            {
                fragment.SetParentOverride(null);
            }
        }
コード例 #20
0
        /// <summary>
        /// Wander behavior.
        /// This behavior is defined by the values of:
        ///     - WanderingRadius    --> Strength of wander
        ///     - WanderingDistance  --> Distance ahead the agent where wander circle is drawn
        ///     - WanderingJitter    --> Max amount of random displacement that can be add each second
        /// Can also be compute using Perlin noise.
        /// </summary>
        private Vector2 Wander(double timeElapsed)
        {
            // Jitter scale according to time elapsed
            double jitterTimeSliced = timeElapsed * WanderingJitter;

            // Create wander target direction using a binomial distribution (-1 ; 1)
            WanderingTarget += new Vector2((float)(RandomHelper.NextBinomial() * jitterTimeSliced),
                                           (float)(RandomHelper.NextBinomial() * jitterTimeSliced));

            // Get normalized direction (projection on a unit circle)
            // Be aware that we cannot normalize using the property because only the copy will be normalized
            // Indeed the Vector is a structure not a class
            _wanderingTarget.Normalize();

            // Scale based on circle radius
            WanderingTarget *= WanderingRadius;
            // Project target ahead of agent
            Vector2 targetLocal = WanderingTarget + new Vector2(WanderingDistance, 0);

            // Get world position based on local basis
            // Vector2 targetWorld = TransformHelper.LocalToWorld(targetLocal, Agent.Heading, Agent.Perp, Agent.Pos);
            Vector2 targetWorld = TransformHelper.LocalToWorldByMatrix(targetLocal, Agent.Heading, Agent.Perp, Agent.Pos);

            // Only used for debug purpose
            wanderTargetPos = targetWorld;
            wanderCirclePos = TransformHelper.LocalToWorldByMatrix(new Vector2(WanderingDistance, 0), Agent.Heading, Agent.Perp, Agent.Pos);

            // Return a force of attraction to random target
            return(Seek(targetWorld));
        }
コード例 #21
0
    /// <summary>
    /// Chamado a cada frame, se o script estiver habilitado.
    /// <remarks>
    /// � chamado ap�s todos os m�todos Update terem sido chamados.
    /// � �til para ordernar a execu��o de scripts. Por exemplo uma c�mera que segue um objeto
    /// deve ser sempre implementada no m�todo LateUpdate, pois ela ir� seguir a posi��o do objeto que foi
    /// alterada no Update de seu script.
    /// </remarks>
    /// </summary>
    public void LateUpdate()
    {
        if (!Target)
        {
            return;
        }

        // Calculate the current rotation angles
        float wantedRotationAngle = Target.eulerAngles.y;
        float wantedHeight        = Target.position.y + Height;

        float currentRotationAngle = transform.eulerAngles.y;
        float currentHeight        = transform.position.y;

        // Damp the rotation around the y-axis
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, RotationDamping * Time.deltaTime);

        // Damp the Height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, HeightDamping * Time.deltaTime);

        // Convert the angle into a rotation
        Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position  = Target.position;
        transform.position -= currentRotation * Vector3.forward * Distance;

        // Set the Height of the camera
        TransformHelper.SetPositionY(transform, currentHeight);

        // Always look at the target
        transform.LookAt(Target);
    }
コード例 #22
0
 private void Awake()
 {
     if (_instance == null)
     {
         _instance = this as TransformHelper;
     }
 }
コード例 #23
0
        public void TestMethod1()
        {
            //用户统计
            //新增
            UsersStatSearchDTO searchdto = new UsersStatSearchDTO();

            searchdto.page = 1;
            searchdto.rows = 1;
            var searchdtostr = TransformHelper.ConvertDTOTOBase64JsonString(searchdto);

            testcontroller.GetUsersStatList(searchdtostr);
            UsersStatOperateDTO adddto = new UsersStatOperateDTO();

            adddto.UseModel     = "单元测试用户统计";
            adddto.UseModelTime = DateTime.Now;
            searchdto.rows      = 20;
            searchdtostr        = TransformHelper.ConvertDTOTOBase64JsonString(searchdto);
            var addresult   = testcontroller.AddUsersStat(adddto);
            var resultlist1 = JsonConvert.DeserializeObject <ResultDTO <List <UsersStatResultDTO> > >(testcontroller.GetUsersStatList(searchdtostr).Content.ReadAsStringAsync().Result).Object;
            var target      = resultlist1.Where(m => m.UseModel == "单元测试用户统计").FirstOrDefault();

            Assert.IsNotNull(target);

            //删除
            UsersStatResultDTO deletedto = new UsersStatResultDTO();

            deletedto.UsersStatID = target.UsersStatID;
            var deletedtostr = TransformHelper.ConvertDTOTOBase64JsonString(deletedto);
            var deleteresult = testcontroller.DeleteUsersStat(deletedtostr);
            var resultlist3  = JsonConvert.DeserializeObject <ResultDTO <List <UsersStatResultDTO> > >(testcontroller.GetUsersStatList(searchdtostr).Content.ReadAsStringAsync().Result).Object;

            target = resultlist3.Where(m => m.UsersStatID == target.UsersStatID).FirstOrDefault();
            Assert.IsNull(target);
        }
コード例 #24
0
    void FixedUpdate()
    {
        if (target == null)
        {
            return;
        }

        var _targetPosition = transform.worldToLocalMatrix.MultiplyPoint3x4(target.transform.position);

        if (_targetPosition.sqrMagnitude > radius * radius)
        {
            return;
        }

        var _targetAngle = TransformHelper.VectorToDeg(_targetPosition);

        if (_targetAngle > range || _targetAngle < -range)
        {
            return;
        }

        var _newAngle = transform.localEulerAngles;

        _newAngle.z += Mathf.Clamp(_targetAngle, -constCatchUp, constCatchUp);
        _newAngle.z += Mathf.Lerp(0, _targetAngle, lerpCatchUp);
        transform.localEulerAngles = _newAngle;
    }
コード例 #25
0
    public void Refresh()
    {
        if (!database)
        {
            return;
        }
        var _tiledata = database[data];

        if (_tiledata == null)
        {
            return;
        }

        collider_.size   = data.sizeWorld;
        renderer_.sprite = GenericHelper.SelectRandom(_tiledata.sprite);

        if (prefab)
        {
#if UNITY_EDITOR
            DestroyImmediate(prefab);
#else
            Destroy(prefab);
#endif
            prefab = null;
        }

        if (_tiledata.prefab)
        {
            prefab = (GameObject)Instantiate(_tiledata.prefab);
            TransformHelper.SetParentLocal(prefab, gameObject);
        }
    }
コード例 #26
0
        private string FindOrAddDataTypeTemplate(string dataTypeName)
        {
            string templateName = "dataType_" + dataTypeName;

            if (this.dataTypeTemplates.ContainsKey(dataTypeName))
            {
                return(templateName);
            }

            SimpleSchema.SchemaObject simpleComplexType = this.simpleSchema.ComplexTypes.SingleOrDefault(y => y.Name == dataTypeName);

            bool dataTypeDefined = this.tdb.ImplementationGuideTypeDataTypes.Count(y =>
                                                                                   y.ImplementationGuideTypeId == this.rootTemplate.ImplementationGuideTypeId &&
                                                                                   y.DataTypeName == dataTypeName) > 0;

            if (simpleComplexType == null || !dataTypeDefined)
            {
                return(string.Empty);
            }

            XmlElement dataTypeTemplate = TransformHelper.CreateXslTemplate(this.transformDoc, templateName, string.Empty);

            dataTypeTemplate.AppendChild(
                TransformHelper.CreateXsltTemplateParam(this.transformDoc, "instance"));

            CompleteDataTypeTemplate(dataTypeTemplate, simpleComplexType, "$instance");
            this.dataTypeTemplates.Add(dataTypeName, dataTypeTemplate);

            return(templateName);
        }
コード例 #27
0
ファイル: FindEnemyDemo.cs プロジェクト: susecury/git0505
    private void OnGUI()
    {
        if (GUILayout.Button("find the enemy with lowest HP"))
        {
            // find all enemy
            Enemy[] allEnemy = Object.FindObjectsOfType <Enemy>();
            // find the min enemy
            Enemy min = FindEnemyByMinHp(allEnemy);
            // sign the enemy
            min.GetComponent <MeshRenderer>().material.color = Color.red;
        }
        if (GUILayout.Button("层级未知,查找子物体"))
        {
            var childTF = TransformHelper.GetChild(this.transform, "Cubexx");
            childTF.GetComponent <MeshRenderer>().material.color = Color.red;
        }

        if (GUILayout.Button("暂停游戏"))
        {
            Time.timeScale = 0;
        }

        if (GUILayout.Button("继续游戏"))
        {
            Time.timeScale = 1;
        }
    }
コード例 #28
0
ファイル: TestScript.cs プロジェクト: XaHDpE/pzl3d
    private void HalfSize(float distance, float viewPortPart)
    {
        var height = 2.0 * Mathf.Tan(0.5f * _mainCam.fieldOfView * Mathf.Deg2Rad) * distance;
        var width  = height * Screen.width / Screen.height;

        var targetSize = (float)Math.Min(height, width);

        Debug.Log($"height: {height}, width: {width}, {Camera.main.fieldOfView}");

        var currentSize = TransformHelper.GetHierarchicalBounds(gameObject).extents.magnitude;
        var currScale   = transform.localScale;

        Debug.Log($"targetSize: {targetSize}, currScale: " +
                  $"{currScale}, currentSize: {currentSize}, " +
                  $"{targetSize * currScale.x / currentSize}");

        /*
         *
         * var newScale = new Vector3(
         *  targetSize * currScale.x / currentSize,
         *  targetSize * currScale.y / currentSize,
         *  targetSize * currScale.z / currentSize
         * );
         *
         * var scaleTo = TransformHelper.ScaleTo(transform, newScale, 5);
         *
         * var exts = GetBounds(gameObject).extents;
         * Debug.Log($"newScale: {newScale}, finalSize: {exts.x}, {exts.y}, {exts.z}");
         */
    }
コード例 #29
0
        public HttpResponseMessage GetFeedbackList(string FeedbackSearchDTO)
        {
            FeedbackSearchDTO dto = TransformHelper.ConvertBase64JsonStringToDTO <FeedbackSearchDTO>(FeedbackSearchDTO);
            ResultDTO <List <FeedbackResultDTO> > actionresult = new ResultDTO <List <FeedbackResultDTO> >();

            try
            {
                actionresult.Object       = _ICommonServices.GetFeedbackList(dto);
                actionresult.SubmitResult = true;
                actionresult.rows         = dto.rows;
                actionresult.page         = dto.page;
                actionresult.Count        = dto.Count;
            }
            catch (Exception ex)
            {
                actionresult.SubmitResult = false;
                actionresult.Message      = ex.Message;
            }
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(JsonConvert.SerializeObject(actionresult),
                                            System.Text.Encoding.GetEncoding("UTF-8"),
                                            "application/json")
            };

            return(result);
        }
コード例 #30
0
        public void OperationEntity_GetServers()
        {
            var openApiDocument = LoadOpenApiDocument("../../samples/GetServers.yaml");
            var serverEntities  = TransformHelper.GetServerEnities(openApiDocument.Servers);

            Assert.NotNull(serverEntities);
            Assert.True(serverEntities.Count == 1);
            Assert.Equal("https://developer.uspto.gov/v1", serverEntities[0].Name);

            Assert.NotNull(serverEntities[0].ServerVariables);
            Assert.True(serverEntities[0].ServerVariables.Count == 2);
            Assert.Equal("scheme", serverEntities[0].ServerVariables[0].Name);
            Assert.Equal("https", serverEntities[0].ServerVariables[0].DefaultValue);
            Assert.Equal("The Data Set API is accessible via https and http", serverEntities[0].ServerVariables[0].Description);
            Assert.Equal(2, serverEntities[0].ServerVariables[0].Values.Count);
            Assert.Equal("https", serverEntities[0].ServerVariables[0].Values[0]);
            Assert.Equal("http", serverEntities[0].ServerVariables[0].Values[1]);

            Assert.Equal("basepath", serverEntities[0].ServerVariables[1].Name);
            Assert.Equal("v1", serverEntities[0].ServerVariables[1].DefaultValue);
            Assert.Equal("the base path", serverEntities[0].ServerVariables[1].Description);
            Assert.Equal(2, serverEntities[0].ServerVariables[1].Values.Count);
            Assert.Equal("v1", serverEntities[0].ServerVariables[1].Values[0]);
            Assert.Equal("v2", serverEntities[0].ServerVariables[1].Values[1]);
        }