Hi there. I am creating a mini game in React. I want my sheep image to be ‘fired’ from the middle of the screen , to the borders, every few seconds. Especially important , I want it to happen while previous images are still on the screen. So , for example, to have 6,7 same images on screen at different random locations, moving from the centre to the borders. I can make one image move, but I don’t know how to make multiple images. Here is my code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import "./bootstrap/css/bootstrap.css";
import {CreateEnvironment} from './components/createEnvironment';
import {SheepsStart} from './components/sheepsStart';
class MainComponent extends React.Component {
render(){
return (
<React.Fragment>
<CreateEnvironment />
<SheepsStart />
</React.Fragment>
);
}
}
ReactDOM.render(<MainComponent/>, document.getElementById('root'));
CreateEnvironment component is creating divs of drawings, not very important here, so I`ll skip it.
SheepsStart.js component:
import React from 'react';
import {CreateSheeps} from './createSheeps';
import sheep from '../images/sheep.png';
export class SheepsStart extends React.Component {
render(){
return (
<React.Fragment>
<CreateSheeps src = {sheep} alt = "Sheep"/>
</React.Fragment>
);
}
}
Styled component, needed it to apply @keyframes:
import styled from 'styled-components';
import { sheepWantsToEscape } from './KeyFrames';
export const CreateSheeps = styled.img`
width:2.5%;
z-index: 1;
position:absolute;
left:48.75%;
bottom:48.75%;
animation: ${sheepWantsToEscape} 4s;
animation-iteration-count:1;
animation-timing-function:linear;
`
export default CreateSheeps;
keyframes.js:
import styled, { keyframes } from 'styled-components';
import {createTrajectory} from './helperFunction';
let coordinates = createTrajectory();
export const sheepWantsToEscape = keyframes`
0% {
left:48.75%;
bottom:48.75%;
}
100% {
left:${coordinates[0]}%;
bottom:${coordinates[1]}%;
}
`
Create trajectory function is calculating random left and bottom values, to create a trajectory for the image.