首页 \ 问答 \ 游戏视口焦点与y轴上的碰撞检测相对于重力(game viewport focus vs collision detection on y axis against gravity)

游戏视口焦点与y轴上的碰撞检测相对于重力(game viewport focus vs collision detection on y axis against gravity)

通过增加'y'值来减少球。

y = 100时有一面墙。

球应该与墙碰撞,两者都应该停止。

另外,我需要一个专注于球的视口。 我尝试沿球的相反方向移动墙壁。

 function update() {
     ballupdate();

     // opposite direction
     var viewportY = - gety('#ball');
     wallupdate(viewportY);
     collision();
     requestAnimationFrame(update);
 }

 function ballupdate() {
     var top = gety('#ball');
     top+= 3;
     top = Math.min(top, 300);
     sety('#ball', top);
 }

 function wallupdate(viewportY) {
     sety('#wall', 100 + viewportY);
 }

如果发生碰撞,则球在墙壁上方移动。

function collision() {
    var balltop = gety('#ball');
    var walltop = gety('#wall');

    if (balltop + getheight('#ball') >= walltop) {
        //console.log(balltop);
        ballhit(walltop - getheight('#ball'));
    }
}

function ballhit(y) {
   sety('#ball', y);
}

这导致球和墙都上下摇晃。 这是一个JSFIDDLE


There is a ball dropping by increasing its 'y' value.

There is a wall at y = 100.

Ball should collide with wall and both should stop.

Also, i need a viewport with a focus on ball. I try moving the wall in the opposite direction of the ball.

 function update() {
     ballupdate();

     // opposite direction
     var viewportY = - gety('#ball');
     wallupdate(viewportY);
     collision();
     requestAnimationFrame(update);
 }

 function ballupdate() {
     var top = gety('#ball');
     top+= 3;
     top = Math.min(top, 300);
     sety('#ball', top);
 }

 function wallupdate(viewportY) {
     sety('#wall', 100 + viewportY);
 }

if there is a collision, ball is moved above the wall.

function collision() {
    var balltop = gety('#ball');
    var walltop = gety('#wall');

    if (balltop + getheight('#ball') >= walltop) {
        //console.log(balltop);
        ballhit(walltop - getheight('#ball'));
    }
}

function ballhit(y) {
   sety('#ball', y);
}

This results in both ball and wall shaking up and down. Here is a JSFIDDLE.


原文:https://stackoverflow.com/questions/23727779
更新时间:2022-02-01 19:02

最满意答案

为什么不将值放在枚举本身上然后枚举?

例如,使用System.ComponentModel Description属性,我们可以将该信息添加到枚举本身,例如:

public enum cardCreate
{
  [Description("General Response")]
  MsgType = 0,

  [Description("V2.0")]
  WSName = 2,

  [Description("OmegaMan")]
  ReplyTo = 3,

  [Description("Windows 10")]
  SourceSystem = 4,
}

因此,当我们调用一个特殊的方法来枚举枚举时,我们可以在其中提取该文本并在以后适当地使用它,例如:

myextensions.GetEnumValues<cardCreate>()
            .Select (ceEnum => new
                        {
                            Original   = ceEnum,
                            IndexValue = (int)ceEnum,
                            Text       = ceEnum.GetAttributeDescription()
                        })

投影(选择)后,动态实体将如下所示:

在此处输入图像描述

甜! 现在,我们将所有信息都放在易于消费的实体中,提供所需的所有信息。

什么? 您需要的不仅仅是字符串描述吗? 然后在enum上创建自定义属性,并根据需要返回所有项目/数据类型。 为此,请参阅我的博客文章C#在对象上使用扩展属性信息


以下是上例中使用的扩展方法:

public static class myextensions
{
   public static IEnumerable<T> GetEnumValues<T>()
   {
       Type type = typeof( T );

       if (!type.IsEnum)
           throw new Exception( string.Format("{0} is not an enum.", type.FullName ));

       FieldInfo[] fields =
           type.GetFields( BindingFlags.Public | BindingFlags.Static );


       foreach (var item in fields)
           yield return (T)item.GetValue( null );
   }


  /// <summary>If an attribute on an enumeration exists, this will return that
   /// information</summary>
   /// <param name="value">The object which has the attribute.</param>
   /// <returns>The description string of the attribute or string.empty</returns>
   public static string GetAttributeDescription( this object value )
   {
       string retVal = string.Empty;
       try
       {
           retVal = value.GetType()
                         .GetField( value.ToString() )
                         .GetCustomAttributes( typeof( DescriptionAttribute ), false )
                         .OfType<DescriptionAttribute>()
                         .First()
                         .Description;

       }
       catch (NullReferenceException)
       {
           //Occurs when we attempt to get description of an enum value that does not exist
       }
       finally
       {
           if (string.IsNullOrEmpty( retVal ))
               retVal = "Unknown";
       }

       return retVal;
   }

}

Why not place the values onto the enum itself and then enumerate?

For example using System.ComponentModel Description attribute we can add that information to the enum itself such as:

public enum cardCreate
{
  [Description("General Response")]
  MsgType = 0,

  [Description("V2.0")]
  WSName = 2,

  [Description("OmegaMan")]
  ReplyTo = 3,

  [Description("Windows 10")]
  SourceSystem = 4,
}

So when we call a special method to enumerate the enum where we can extract that text and use it appropriately later such as:

myextensions.GetEnumValues<cardCreate>()
            .Select (ceEnum => new
                        {
                            Original   = ceEnum,
                            IndexValue = (int)ceEnum,
                            Text       = ceEnum.GetAttributeDescription()
                        })

The dynamic entity will look like this after the projection (the select):

enter image description here

Sweet! Now we have all the information in a easy consumable entity which provides all the information needed.

What? You need more than a string description? Then create a custom attribute on the enum and have all items/types of data to return as needed. For that see my blog article C# Using Extended Attribute Information on Objects.


Here are the extension methods used in the above example:

public static class myextensions
{
   public static IEnumerable<T> GetEnumValues<T>()
   {
       Type type = typeof( T );

       if (!type.IsEnum)
           throw new Exception( string.Format("{0} is not an enum.", type.FullName ));

       FieldInfo[] fields =
           type.GetFields( BindingFlags.Public | BindingFlags.Static );


       foreach (var item in fields)
           yield return (T)item.GetValue( null );
   }


  /// <summary>If an attribute on an enumeration exists, this will return that
   /// information</summary>
   /// <param name="value">The object which has the attribute.</param>
   /// <returns>The description string of the attribute or string.empty</returns>
   public static string GetAttributeDescription( this object value )
   {
       string retVal = string.Empty;
       try
       {
           retVal = value.GetType()
                         .GetField( value.ToString() )
                         .GetCustomAttributes( typeof( DescriptionAttribute ), false )
                         .OfType<DescriptionAttribute>()
                         .First()
                         .Description;

       }
       catch (NullReferenceException)
       {
           //Occurs when we attempt to get description of an enum value that does not exist
       }
       finally
       {
           if (string.IsNullOrEmpty( retVal ))
               retVal = "Unknown";
       }

       return retVal;
   }

}

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)