最近在考虑用 DOM 实现 2D 游戏基本动作,其中需要实现精灵(sprite)的行走,跳跃等动作,因为 Canvas 才刚开始学习,于是便想用 CSS3 来实现这个动作。
首先从 dribbble 上找来某位大师的作品:
作为 2D 游戏,要响应键盘的动作就肯定不能直接使用 Gif 图了,于是在 Photoshop 中打开这张图,提取出所有帧:
扣去背景以后拼接成雪碧图:
然后利用 CSS3 的 keyframes 自定義动画:
$spriteWidth: 140px; // 精灵宽度
@keyframes run {
0% {
background-position: 0 0;
}
100% {
background-position: -($spriteWidth * 12) 0; // 12帧
}
}
#sprite {
width: $spriteWidth;
height: 144px;
background: url("../images/sprite.png") 0 0 no-repeat;
animation: run 0.6s steps(12) infinite;
}
实现效果如下:
https://idiotwu.me/css3-running-animation/
其中用到 animation-timing-function 里的 steps() , steps([, [ start | end ] ]?):第一个参数number为指定的间隔数,即把动画分为n步阶段性展示,第二个参数默认为end,设置最后一步的状态,start为结束时的状 态,end为开始时的状态,若设置与animation-fill-mode的效果冲突,而以animation-fill-mode的设置为动画结束的 状态。
所以 animation-timing-function: steps(12) 就相当于:
@keyframes run {
0% { background-position: 0 0; }
8.33% { background-position: -140px 0; }
16.67% { background-position: -280px 0; }
25% { background-position: -420px 0; }
33.33% { background-position: -560px 0; }
41.67% { background-position: -700px 0; }
50% { background-position: -840px 0; }
58.33% { background-position: -980px 0; }
66.67% { background-position: -1120px 0; }
75% { background-position: -1260px 0; }
83.33% { background-position: -1400px 0; }
91.67% { background-position: -1540px 0; }
100% { background-position: 0 0; }
}
#player { animation-timing-function: step-start; }
至此,就完成了人物奔跑动作的实现。
網頁設計.RWD響應式網站 / 教育人文類
網站技術:PHP . Javascript/MySql
青林是專門販售0~12歲以上各年齡書籍的線上書城,每本書籍都是精心挑選才會在網站上進行販售,確保孩子們可以安心閱讀與學習。 網站上會舉行線上書展或是特價活動,或是邀請畫冊、故事書作家來做分享新書。
精選專案.網頁設計.RWD響應式網站 / 休閒餐飲類
網站技術:PHP . Javascript/MySql . ORACLE
RWD響應式網站設計/網頁設計,網頁切版,後台程式管理,可於各種裝置進行網頁瀏覽(PC、平板、手機)。
精選專案.網頁設計.RWD響應式網站.行動版網站 / 服務類
網站技術:Javascript
智慧財產局為提供使用者線上申請專利商標,以及商標申請進度查詢等服務,因此特別規劃此系統讓大眾更為便利,包含的業務申請、繳費、查詢到線上協助等眾多智慧財產權相關的服務內容。
電話:(02)2739-9096 | 傳真:(02)2739-6637 | 客服:[email protected] | 臺北市信義區和平東路3段257號6樓map
© 2019 傑立資訊 All rights reserved.| 網站隱私政策